首页 > 解决方案 > 带有帖子和自定义字段的 Wordpress 搜索

问题描述

大家好,我目前正在 wordpress 中构建搜索功能,我可以搜索帖子类型,但在搜索与帖子类型相关的自定义字段时遇到问题。这是代码,我宁愿不使用任何搜索插件或全局变量。(除非必要)

class Search {

public function __construct() {
    add_filter( 'pre_get_posts', array( $this, 'posts_filter' ) );
}

public function posts_filter( $query ) {
    if ( is_admin() || ! $query->is_main_query() || ! is_search() ) {
        return $query;
    }

    $meta_query = array(
        'relation' => 'OR',
        array(
            'relation' => 'OR',
            array(
                'key' => 'book_writer',
                'value' => get_search_query(),
                'compare' => 'LIKE',
            ),
            array(
                'key' => 'book_isbn',
                'value' => get_search_query(),
                'compare' => 'LIKE',
            ),
        ),
    );

    $query->set('meta_query', $meta_query);
    $query->set( 'post_type', 'book' );
    return $query;
}
}

我不知道如何将这些自定义字段添加到 $query 中,但是像这样它只返回帖子类型“book”(如果我传递了正确的名称)并且如果我搜索 ISBN,例如搜索不'不返回任何结果。

感谢大家

标签: phpwordpress

解决方案


试试这个

class Search {

public function __construct() {
    add_action( 'pre_get_posts', [ $this, 'posts_filter' ] );
}

public function posts_filter( $query ) {
    if ( is_admin() || ! $query->is_main_query() || ! is_search() ) {
        return $query;
    }

    $meta_query = [
        'relation' => 'OR',
            [ 
                'key' => 'book_writer',
                'value' => $query->query['s'],
                'compare' => 'LIKE',
            ],
            [
                'key' => 'book_isbn',
                'value' => $query->query['s'],
                'compare' => 'LIKE',
            ],
    ];

    $query->set('meta_query', $meta_query);
    $query->set( 'post_type', 'book' );
   }
}

从官方文档中,描述了 meta_query 的语法 https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters


推荐阅读