从Wordpress中的另一个过滤器添加/删除过滤器

时间:2020-10-10 07:44:09

标签: php wordpress

我正在尝试根据我当前所在页面的页面作者来添加/删除Wordpress搜索过滤器。搜索栏位于主题标题中,因此与我所在的页面无关。我想使用当前页面的作者ID为我在搜索栏中进行的下一次搜索添加过滤器。

这是一个电子商务网站。搜索栏位于页眉(与页面无关)中。我在商店页面上。我想搜索与搜索操作之前我所在的商店页面相关的产品(即具有相同作者ID的帖子)。

我已经为functions.php编写了代码,但是它不起作用,即未添加(或删除)“ my_search_filter”。我想念的是什么?

function search_filter_by_page_author()
{
    $author_id = get_the_author_meta('ID');
    
    #echo $author_id;

    if (in_array($author_id, array("1", "2"))
    {       
        add_filter( 'pre_get_posts', 'my_search_filter' );      
    }
    else
    {
        remove_filter( 'pre_get_posts', 'my_search_filter' );
    }
}
add_action( 'wp_head', 'search_filter_by_page_author' );

function my_search_filter( $query )
{
    if ( $query->is_search && !is_admin())
    {
        $query->set( 'author', '1, 2' );
    }   
    return $query;
}

1 个答案:

答案 0 :(得分:0)

以下是您所追求的答案。我认为您应该

  1. 设置一个新的searchform.php
  2. 添加您的pre_get_posts(顺便说一下,这是一项操作,而不是过滤器)

searchform.php(示例)-这位于主题或子主题的根文件夹中。

<?php 

global $post;
$author_id = $post->post_author;?>

<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>" role="search" class="searchform search">
    <div class="form-group">
        <input type="text" class="form-control" name="s" value="<?php echo esc_attr( get_search_query() ); ?>" id="s" placeholder="<?php esc_attr_e( 'Search &hellip;', 'text_domain' ); ?>"/>
        <input type="hidden" name="author" value="<?php echo $author_id;?>">
    </div>
    <button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button>
</form>

搜索过滤器(放入functions.php中)

add_action('pre_get_posts', 'search_filter_by_page_author');
function search_filter_by_page_author($query){
  
  if ($query->is_search && !is_admin() && isset($_GET['author'])) {
    $query->set('author', $_GET['author']);
  }
  return $query;
}

这可能并不能完全满足您的需求,但是我认为您应该可以从中获得积极的结果。