0

I want to expand the Wordpress admin panel search using this code.

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

    $s = get_search_query();

    $query->set( 'meta_query', [
        'relation' => 'OR',
        [
            'meta_key'     => '_company_inn',
            'value'   => $s,
            'compare' => 'LIKE',
        ],
        [
            'meta_key'     => '_company_phone',
            'value'   => $s,
            'compare' => 'LIKE',
        ],
    ] );

    $query->set( 'post_type', 'company' );
}
add_filter( 'pre_get_posts', 'add_search_query_meta' );

function modify_where_search_request( $where )
{
    if ( is_admin() || ! is_main_query() || ! is_search() )
        return $where;

    global $wpdb;

    $s = get_search_query();

    $where = preg_replace(
        [
            "~ OR \({$wpdb->posts}.post_[^\s]+ (LIKE '(?:%|{[^}]+}){$s}(?:%|{[^}]+})')\)~i", // убираем поиск по контенту и цитате
            "~AND\s+([\s(]+{$wpdb->wp_pn_companymeta}.meta_key)~i" // меняем AND условие мета-запроса на OR
        ],
        [
            '',
            'OR $1'
        ],
        $where
    );

    return $where;
}
add_action( 'posts_where_request', 'modify_where_search_request' );

Database structure:

enter image description here

Here are the keys I'm trying to access and get the value of: enter image description here

I don't understand how to get these values through a standard search, help please..

Here is the link to the plugin

1 Answer 1

0

For regular admin panel search you should include "is_admin()" to be true. For checking for specific post type you should check from $query->get("post_type")

Can you try to use this code

 add_action("pre_get_posts", function ($query) {
    if ($query->is_main_query() && is_admin() && in_array($query->get('post_type'), array('company'))) {
        $s = get_search_query();
        $meta_query = [
            'relation' => 'OR',
            [
                'meta_key'     => '_company_inn',
                'value'   => $s,
                'compare' => 'LIKE',
            ],
            [
                'meta_key'     => '_company_phone',
                'value'   => $s,
                'compare' => 'LIKE',
            ],
        ];
        $query->set("s", $s);
        $query->set("meta_query", $meta_query);
    }

    return $query;
});
1
  • Thank you very much for the feedback, but it didn't work for me :( After inserting this code, the Title search disappears Commented Feb 12 at 7:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.