【问题标题】:How to target specific search form with pre_get_posts?如何使用 pre_get_posts 定位特定的搜索表单?
【发布时间】:2015-04-04 13:21:24
【问题描述】:

在我的博客页面上,我有 2 个默认的 wordpress 搜索表单,1 个在标题中应该搜索所有内容,1 个在侧边栏中,应该只搜索帖子。

我设法使用 pre_get_posts 更改为查询以满足我的需求,但它会针对两种搜索表单进行更改

function exclude_pages($query) {
  if ($query->is_home() && $query->is_main_query() && !is_admin() ) {
    $query->set('post_type', 'post');
  }
}

add_action('pre_get_posts', 'exclude_pages');

如何指定该函数仅更改侧栏中搜索表单的查询?

【问题讨论】:

    标签: php search wordpress


    【解决方案1】:

    将隐藏字段添加到您的搜索表单之一,然后检查是否已在 pre_get_posts 中为其设置了值。

    在侧边栏表单内添加:

    <input type="hidden" name="posts-only" value="1" />
    

    然后改变这个:

    if ($query->is_home() && $query->is_main_query() && !is_admin() ) {
        $query->set('post_type', 'post');
    }
    

    收件人:

    // Check if posts only value has been set and equal to 1. Return if not.
    if ( ! isset( $_GET['posts-only'] ) || 1 !== $_GET['posts-only'] ) {
        return false;
    }
    
    if ( $query->is_home() && $query->is_main_query() && ! is_admin() ) {
        $query->set( 'post_type', 'post') ;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 2013-05-06
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      相关资源
      最近更新 更多