如何 select a Post Type (Wordpress) 在 head 中传递过滤器?
How to select a Post Type (Wordpress) to pass a filter in head?
我有一个使用 Yoast SEO 来管理 canonical links 和 noindex meta robots 等的 WordPress 网站东西,具有非常奇特的配置。
默认情况下,Yoast 的插件会在每个页面中添加一个 <link rel="canonical" href="...">
。我对在每个静态页面(无论其类型是什么)中显示规范的 link 不感兴趣,但在某些类型的 post 中显示:Pages 和 帖子(不是附件、类别、存档等)
我知道防止 Yoast 默认添加规范 link 的方法,只需在 functions.php 中添加以下代码:add_filter( 'wpseo_canonical', '__return_false' );
。但是,如果我只想在某些 post 类型中传递该过滤器怎么办?或者在除某些类型的 post 之外的每个页面中传递它(这两种方法对我都很有用)。帮助将不胜感激。有吗?
更新:有效答案并进行了一些小修正
function remove_canonical_from_post_types($url) {
$post_type = get_post_type();
if ($post_type !== 'post' && $post_type !== 'page') { // If post type is not Post nor Page, doesn't add a canonical link in any case
return false;
}
else { // It is Post or Page
if (is_category() || is_author() || is_tag() || is_archive()) { // If page is post type 'Post' we don't want to add canonical in some sub-types: Category, Author, Tag, Archive
return false;
}
return $url; // In any other case (Posts and Pages) adds a canonical link
}
}
add_filter('wpseo_canonical', 'remove_canonical_from_post_types');
尝试使用提供的 "wpseo_canonical" 过滤器并检查 post 类型是否正确(以及 return 错误)。
像这样:
function remove_canonical_from_post_types($url)
{
$post_type = get_post_type();
if ($post_type !== 'post' && $post_type !== 'page') {
return false;
}
return $url;
}
add_filter('wpseo_canonical', 'remove_canonical_from_post_types');
我有一个使用 Yoast SEO 来管理 canonical links 和 noindex meta robots 等的 WordPress 网站东西,具有非常奇特的配置。
默认情况下,Yoast 的插件会在每个页面中添加一个 <link rel="canonical" href="...">
。我对在每个静态页面(无论其类型是什么)中显示规范的 link 不感兴趣,但在某些类型的 post 中显示:Pages 和 帖子(不是附件、类别、存档等)
我知道防止 Yoast 默认添加规范 link 的方法,只需在 functions.php 中添加以下代码:add_filter( 'wpseo_canonical', '__return_false' );
。但是,如果我只想在某些 post 类型中传递该过滤器怎么办?或者在除某些类型的 post 之外的每个页面中传递它(这两种方法对我都很有用)。帮助将不胜感激。有吗?
更新:有效答案并进行了一些小修正
function remove_canonical_from_post_types($url) {
$post_type = get_post_type();
if ($post_type !== 'post' && $post_type !== 'page') { // If post type is not Post nor Page, doesn't add a canonical link in any case
return false;
}
else { // It is Post or Page
if (is_category() || is_author() || is_tag() || is_archive()) { // If page is post type 'Post' we don't want to add canonical in some sub-types: Category, Author, Tag, Archive
return false;
}
return $url; // In any other case (Posts and Pages) adds a canonical link
}
}
add_filter('wpseo_canonical', 'remove_canonical_from_post_types');
尝试使用提供的 "wpseo_canonical" 过滤器并检查 post 类型是否正确(以及 return 错误)。
像这样:
function remove_canonical_from_post_types($url)
{
$post_type = get_post_type();
if ($post_type !== 'post' && $post_type !== 'page') {
return false;
}
return $url;
}
add_filter('wpseo_canonical', 'remove_canonical_from_post_types');