脚本解决方案的基本问题是:rel_canonical
不提供任何有用的过滤器。因此,我们必须替换该函数:
remove_action( 'wp_head', 'rel_canonical' );
add_action( 'wp_head', 't5_canonical_subpages' );
下一个问题:$GLOBALS['numpages']
之前为空setup_postdata()
。我们已经可以在这里调用该函数了,但是它可能会有副作用。
这是一个解决方案,它也添加了正确的上一个/下一个链接,并且可以防止引起的冲突关系adjacent_posts_rel_link_wp_head
。我们在wp_head
不晚于优先级9的情况下也加入了钩子,无法停用后一个钩子。
remove_action( 'wp_head', 'rel_canonical' );
add_action( 'wp_head', 't5_canonical_subpages', 9 );
/**
* Extend version of the native function rel_canonical()
*
* @wp-hook wp_head
* @return void
*/
function t5_canonical_subpages()
{
if ( ! is_singular() )
return;
if ( ! $id = $GLOBALS['wp_the_query']->get_queried_object_id() )
return;
$post = get_post( $id );
setup_postdata( $post );
# let WordPress do all the work
if ( empty ( $GLOBALS['page'] ) )
return rel_canonical();
$permalink = get_permalink( $id );
$canonical = t5_page_permalink( $permalink, $GLOBALS['page'] );
echo "<link rel='canonical' href='$canonical' />";
# next and prev links
if ( 1 < $GLOBALS['page'] )
{
$prev = t5_page_permalink( $permalink, $GLOBALS['page'] - 1 );
print "<link rel='prev' href='$prev' />";
}
if ( isset ( $GLOBALS['numpages'] ) && $GLOBALS['page'] < $GLOBALS['numpages'] )
{
$next = t5_page_permalink( $permalink, $GLOBALS['page'] + 1 );
print "<link rel='next' href='$next' />";
}
# avoid conflicting pev/next links
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head' );
}
/**
* Helper to get correct permalinks for sub-pages.
*
* @param string $permalink
* @param int $page
* @return string
*/
function t5_page_permalink( $permalink, $page )
{
if ( 1 == $page )
return $permalink;
# no pretty permalinks
if ( '' === get_option( 'permalink_structure' ) )
return add_query_arg( 'page', $page, $permalink );
return $permalink . user_trailingslashit( $page, 'single_paged' );
}