wp_head()で出力されるcanonicalだと不十分なので、テンプレートタグに頼らず自前でコードを出力するための基本設定です。
出力されるソースは以下の通りです。
rel="canonical" と rel="next/prev" を出力します。
<link rel="canonical" href="http://xxxxsample.com/abc" />
<link rel="next" href="http://xxxxsample.com/abc/page/2" />
テンプレートタグからcanonical出力を無効化
まずはwp_head()からcanonicalを出力させないよう無効化しましょう。
function.php
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
remove_action('wp_head', 'rel_canonical');
<head>~</head>内にコードを追加
header.phpの適当な箇所に以下コードを追加。
header.php
<?php
global $page, $paged, $wp_query;
// ホーム
if(is_home()||is_front_page()){
$canonical_url = home_url();
// カテゴリーページ
}else if (is_category()){
$canonical_url = get_category_link(get_query_var('cat'));
// 固定ページ&個別記事
} else if (is_page()||is_single()) {
$canonical_url = get_permalink();
// 検索結果ページ
} else if (is_search()){
$encode_s_word = urlencode(get_search_query());
$canonical_url = home_url().'?s='.$encode_s_word;
// タグアーカイブページ
} else if(is_tag()){
$encode_tag = urlencode(single_tag_title( '', false ));
$canonical_url = home_url().'/archives/tag/'.$encode_tag;
// その他
} else {
$canonical_url = null;
}
if ($canonical_url == !null) { ?><link rel="canonical" href="<?php echo $canonical_url; ?>" />
<?php }
// 2ページ目以降がある場合
// rel="next" href="~" を出力
if (!$max_page)
$max_page = $wp_query->max_num_pages;
if (!$paged)
$paged = 1;
$nextpage = intval($paged) + 1;
if (!is_singular() && ($nextpage <= $max_page)) { ?>
<link rel="next" href="<?php echo next_posts( $max_page, false ); ?>" />
<?php } /* end if */
// rel="prev" href="~" を出力
if(!is_singular() && $paged > 1){ ?>
<link rel="prev" href="<?php echo previous_posts( false ); ?>" />
<?php } /* end if */ ?>
※日本語はエンコードされます。