如何从搜索结果中排除wordpress页面模板(自定义模板)?

shi*_*iro 8 php wordpress wordpress-theming

我创建了自定义页面模板。

<?php
/*
 * Template Name: foo
 */
?>
Run Code Online (Sandbox Code Playgroud)

该文件名为“foo.php”。

我试过

global $query_string;
query_posts($query_string . "&post_type=post");
Run Code Online (Sandbox Code Playgroud)

但所有页面都将被排除......

如何从 WordPress 搜索结果中仅排除此页面模板?

小智 7

对于任何偶然发现此线程并且在 WP 新版本上没有成功的人:必须设置 $query args,而不是重做 query_posts... 如下所示:

// exclude any content from search results that use specific page templates
function exclude_page_templates_from_search($query) {

    global $wp_the_query;
    if ( ($wp_the_query === $query) && (is_search()) && ( ! is_admin()) ) {

            $query->set(
                'meta_query',
                array(
          array(
              'key' => '_wp_page_template',
              'value' => 'page-template-1.php',
              'compare' => '!='
              )
          )
      );
    }

}
add_filter('pre_get_posts','exclude_page_templates_from_search');
Run Code Online (Sandbox Code Playgroud)


Flo*_*ian 5

Nicolay提到的查询非常方便,但它也会从搜索结果中删除所有帖子,因为帖子不包含密钥'_wp_page_template'。要拥有所有页面(没有过滤的模板)以及所有帖子,您需要执行以下操作:

// exclude any content from search results that use specific page templates
function exclude_page_templates_from_search($query) {
    global $wp_the_query;
    if ( ($wp_the_query === $query) && (is_search()) && ( ! is_admin()) ) {
        $meta_query = 
            array(
// set OR, default is AND
                'relation' => 'OR',
// remove pages with foo.php template from results
                array(
                    'key' => '_wp_page_template',
                    'value' => 'foo.php',
                    'compare' => '!='
                ),
// show all entries that do not have a key '_wp_page_template'
                array(
                    'key' => '_wp_page_template',
                    'value' => 'page-thanks.php',
                    'compare' => 'NOT EXISTS'
                )
            );
        $query->set('meta_query', $meta_query);
    }
}
add_filter('pre_get_posts','exclude_page_templates_from_search');
Run Code Online (Sandbox Code Playgroud)

有关这方面的大量信息可以在 WordPress Codex 中找到。


Nik*_*nov 4

尝试这个:

global $wp_query;
$args = array_merge($wp_query->query, array(
    'meta_query' => array(
        array(
            'key' => '_wp_page_template',
            'value' => 'foo.php',
            'compare' => '!='
        )
    ),
));
query_posts( $args );
Run Code Online (Sandbox Code Playgroud)