为WordPress网站全部页面添加Canonical标签避免重复内容

在网站优化上为页面设置canonical标签这是必做的一项,该标签的作用应该大家都有所了解,wordpress程序在文章页也提供的有canonical标签,但是功能上不太完善,现在网上关于设置canonical标签的帖子也非常多,但是很多都是过时的或者只能为首页,分类页,文章也设置,像作者页面,归档页面还有标签页面就没有设置的方法了,今天我给大家分享一段布置简单,功能全面的代码。

 什么是canonical标签

引用:rel=”canonical” 这个标签已经推出很久了,canonical 是 Google、雅虎、微软等搜索引擎一起推出的一个标签,它的主要作用是用来解决由于网址形式不同内容相同而造成的内容重复问题。这个标签对搜索引擎作用非常大,简单的说它可以让搜索引擎只抓取你想要强调的内容。(百度目前也支持这个标签)

举个例子:

  1. https://themege.net/cx-images-001.html
  2. https://themege.net/cx-images-001.html/1
  3. https://themege.net/cx-images-001.html/2

这三个网址形式不同,第一个才是我们想显示给搜索引擎和用户的网址,但是打开它们网站的内容却是相同的。一般像这种状况搜索引擎是很难分辨出来哪个才是网站主想要强调的网址,这样会直接造成搜索引擎在你的站里面收录到大量重复的内容,现在我们通过 canonical 标签就可以解决这些棘手的问题了。

 wordpress代码

/* ——————————– */
function cx_archive_link( $paged = true ) {
        $link = false;
        if ( is_front_page() ) {
                $link = home_url( '/' );
        } else if ( is_home() && "page" == get_option('show_on_front') ) {
                $link = get_permalink( get_option( 'page_for_posts' ) );
        } else if ( is_tax() || is_tag() || is_category() ) {
                $term = get_queried_object();
                $link = get_term_link( $term, $term->taxonomy );
        } else if ( is_post_type_archive() ) {
                $link = get_post_type_archive_link( get_post_type() );
        } else if ( is_author() ) {
                $link = get_author_posts_url( get_query_var('author'), get_query_var('author_name') );
        } else if ( is_single() ) {
                $link = get_permalink( $id );
        } else if ( is_archive() ) {
                if ( is_date() ) {
                        if ( is_day() ) {
                                $link = get_day_link( get_query_var('year'), get_query_var('monthnum'), get_query_var('day') );
                        } else if ( is_month() ) {
                                $link = get_month_link( get_query_var('year'), get_query_var('monthnum') );
                        } else if ( is_year() ) {
                                $link = get_year_link( get_query_var('year') );
                        }
                }
        }
        if ( $paged && $link && get_query_var('paged') > 1 ) {
                global $wp_rewrite;
                if ( !$wp_rewrite->using_permalinks() ) {
                        $link = add_query_arg( 'paged', get_query_var('paged'), $link );
                } else {
                        $link = user_trailingslashit( trailingslashit( $link ) . trailingslashit( $wp_rewrite->pagination_base ) . get_query_var('paged'), 'archive' );
                }
        }
        echo '';
}
add_action('wp_head', 'cx_archive_link');

 添加方式

代码的布局非常简单把上面的这段代码添加到主题的functions.php文件中即可,注意请勿使用记事本编辑php文件,如果可以直接在wordpress后台=>外观=>编辑=>找到functions.php(模板函数)进行修改!

 

阅读全文
常见问题
下载地址失效了怎么版?
客服会第一时间检查下载地址,并发送到您的注册邮箱。如未及时处理可联系客服QQ或邮箱。
导入演示被中断了想重新导入怎么办?
https://themege.net/23822.html
不懂导入演示数据?无法一键导入演示数据?
https://themege.net/16186.html
原文链接:https://themege.net/6150.html,转载请注明出处。
0

评论0

请先