0

I'd like to transfor the following code. This code was done to add a specific search for post ID numbers. Now I need a function to extend the search to a meta field called "function_name", and the search is not public but from the admin post table

function search_by_post_id( $query ) {
    if ( $query->is_search ) {
        if ( is_numeric( $query->query_vars['s'] ) ) {
            $query->set( 'post_type', 'any' );
            $query->set( 'post__in', array( (int) $query->query_vars['s'] ) );
            $query->set( 's', '' );
        }
    }

    return $query;
}
add_filter( 'pre_get_posts', 'search_by_post_id' );
1
  • The hook pre_get_posts is an action, not a filter: change add_filter() to add_action() and remove return $query.
    – Caleb
    Commented Jun 12, 2023 at 15:08

1 Answer 1

0

You can use the meta_query parameter of WP_Query to search custom fields.

Untested:

$meta_query = $query->get( 'meta_query', array() );

$meta_query[] = array(
    'key'     => 'function_name',
    'value'   => $query->query_vars['s'],
    'compare' => 'LIKE',
);

$query->set( 'meta_query', $meta_query );
2
  • I suppose I have to complete the function and start with function search_by_meta($meta_query) { Commented Jun 13, 2023 at 6:26
  • Up to you how you implement, though you'll still use the pre_get_posts hook, so your parameter wouldn't be $meta_query.
    – Caleb
    Commented Jun 13, 2023 at 12:57

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.