最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to create a WP_Query to search the Title or Tag?

programmeradmin0浏览0评论

I have created a search using WP_Query, it seems like this query is looking for the queried term in title AND tags.

Is there a way to have this search the title OR tags?

$s = $request['s'];
$tags = str_replace(' ', '-', strtolower($request['s']));

$paged = $request['page'];
$posts_per_page = $request['per_page'];

$result = new WP_Query([
    'post_type'         => 'post',
    'category__in'      => 3060,
    'posts_per_page'    => $posts_per_page,
    'paged'             => $page,
    'orderby'           => 'date',
    'order'             => 'desc',
    's'                 => $s,
    'tag'               => array($tags)
]);

I have created a search using WP_Query, it seems like this query is looking for the queried term in title AND tags.

Is there a way to have this search the title OR tags?

$s = $request['s'];
$tags = str_replace(' ', '-', strtolower($request['s']));

$paged = $request['page'];
$posts_per_page = $request['per_page'];

$result = new WP_Query([
    'post_type'         => 'post',
    'category__in'      => 3060,
    'posts_per_page'    => $posts_per_page,
    'paged'             => $page,
    'orderby'           => 'date',
    'order'             => 'desc',
    's'                 => $s,
    'tag'               => array($tags)
]);
Share Improve this question asked Jan 15, 2019 at 13:54 Matthew WoodardMatthew Woodard 2263 silver badges14 bronze badges 1
  • Do you want to search in tags, or treat the search query as potential slug of tag? – Krzysiek Dróżdż Commented Jan 28, 2019 at 7:53
Add a comment  | 

2 Answers 2

Reset to default 1

Please use below code to show posts in texonomy and titles

$s = $request['s'];
$tags = str_replace(' ', '-', strtolower($request['s']));

$q1 = get_posts(array(
        'fields' => 'id',
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        's' =>  $s 

));
 $q2 = get_posts(array(
        'fields' => 'ids',
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'tag' => array($tags)
));
$unique = array_unique( array_merge( $q1, $q2 ) );

$posts = get_posts(array(
    'post_type' => 'post',
    'post__in' => $unique,
    'posts_per_page' => -1
));
  if ($posts ) : 

foreach( $posts as $post ) :
//show results
endforeach;
endif;

You just need to add

 'relation' => 'OR'

in your Query arguments. add it and it will return the data with OR condition.

Hope it helps.

发布评论

评论列表(0)

  1. 暂无评论