停止显示自定义帖子类型的wordpress搜索

igl*_*bob 3 wordpress search

我使用一种自定义帖子类型,用于使用uncode主题构建的页面上的某些文本块。我需要将这些块公开,以便它们显示在页面上,但是我想阻止它们出现在搜索结果中。

search.php不像普通的wordpress搜索文件,它是uncode-theme文件,并且没有普通的查询,所以我想也许我需要一个函数?

有人可以建议如何实现吗?

CPT是“ staticcontent”

谢谢!

Gre*_*ett 10

答案取决于您是通过自己的代码创建CPT,还是由其他插件创建CPT。有关此两种方法的详细说明,请参见此链接:

http://www.webtipblog.com/exclude-custom-post-type-search-wordpress/

基本要点是:

如果您要创建自己的CPT,则可以在的register_post_type()调用中添加一个参数 'exclude_from_search' => true

如果另一个插件/主题正在创建CPT,则稍后需要设置此exclude_from_search变量,作为CPT过滤器的一部分,如下所示:

// functions.php

add_action( 'init', 'update_my_custom_type', 99 );

function update_my_custom_type() {
    global $wp_post_types;

    if ( post_type_exists( 'staticcontent' ) ) {

        // exclude from search results
        $wp_post_types['staticcontent']->exclude_from_search = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 警告!这个接受的答案有副作用:它还会导致包含从搜索中排除的帖子类型的分类法的分页不可用。这里有更多详细信息/sf/ask/578879941/ (2认同)

Jon*_*man 6

我认为接受的答案是正确的。exclude_from_search防止所有人$query = new WP_Query返回结果。

核心说:

...检索修订版和将'exclude_from_search'设置为TRUE的类型以外的任何类型)

这是一个常见问题,并且与前端搜索结果页面与数据库中的搜索帖子混在一起。

在前端使用自定义查询来呈现内容,需要exclude_from_search = false或使用另一种方法并直接通过id获取内容。

您需要改为过滤搜索前端机制。这是真正的从搜索中排除帖子类型,而无需手动重建“已知”类型:

function entex_fn_remove_post_type_from_search_results($query){

    /* check is front end main loop content */
    if(is_admin() || !$query->is_main_query()) return;

    /* check is search result query */
    if($query->is_search()){

        $post_type_to_remove = 'staticcontent';
        /* get all searchable post types */
        $searchable_post_types = get_post_types(array('exclude_from_search' => false));

        /* make sure you got the proper results, and that your post type is in the results */
        if(is_array($searchable_post_types) && in_array($post_type_to_remove, $searchable_post_types)){
            /* remove the post type from the array */
            unset( $searchable_post_types[ $post_type_to_remove ] );
            /* set the query to the remaining searchable post types */
            $query->set('post_type', $searchable_post_types);
        }
    }
}
add_action('pre_get_posts', 'entex_fn_remove_post_type_from_search_results');
Run Code Online (Sandbox Code Playgroud)

备注$post_type_to_remove = 'staticcontent';可以更改为适合任何其他帖子类型。

如果我在这里遗漏了一些东西,请发表评论,我无法找到另一种方法来防止这种情况,即通过查询显示内容,对搜索隐藏/直接访问前端用户。

  • 我觉得应该向未来的谷歌用户(比如我自己)明确说明这一点:这种技术可能是您想要的,而不是公认的答案。在 CPT 配置中使用 `'exclude_from_search' => true` (按照已接受答案的建议)**还将从分类存档中删除帖子**,这可能不是您想要的。我自己刚刚经历过这个(WP 5.3.2),你可以在接受的答案的评论中看到OP也经历过它。如果您只想影响搜索结果页面,请使用此答案中的方法。 (3认同)