Search by Custom Field content OR post id via the WordPress Dashboard

admin2025-01-08  5

This codes works fine for searching by custom field content, but could someone help me to modify it so I can search by post id instead of one of the three custom fields? I will only ever search for one of the 4 possible options never multiple.

add_action( 'pre_get_posts', 'extend_admin_search' );
function extend_admin_search( $query ) {
$post_type = 'properties';
$custom_fields = array("custom_field_one","custom_field_two","custom_field_three",);
if( ! is_admin() )
    return;
if ( $query->query['post_type'] != $post_type )
    return;
$search_term = $query->query_vars['s'];

$query->query_vars['s'] = '';

if ( $search_term != '' ) {
    $meta_query = array( 'relation' => 'OR' );
    foreach( $custom_fields as $custom_field ) {
        array_push( $meta_query, array(
            'key' => $custom_field,
            'value' => $search_term,
            'compare' => 'LIKE'
        ));
    }
    $query->set( 'meta_query', $meta_query );
};

}

This codes works fine for searching by custom field content, but could someone help me to modify it so I can search by post id instead of one of the three custom fields? I will only ever search for one of the 4 possible options never multiple.

add_action( 'pre_get_posts', 'extend_admin_search' );
function extend_admin_search( $query ) {
$post_type = 'properties';
$custom_fields = array("custom_field_one","custom_field_two","custom_field_three",);
if( ! is_admin() )
    return;
if ( $query->query['post_type'] != $post_type )
    return;
$search_term = $query->query_vars['s'];

$query->query_vars['s'] = '';

if ( $search_term != '' ) {
    $meta_query = array( 'relation' => 'OR' );
    foreach( $custom_fields as $custom_field ) {
        array_push( $meta_query, array(
            'key' => $custom_field,
            'value' => $search_term,
            'compare' => 'LIKE'
        ));
    }
    $query->set( 'meta_query', $meta_query );
};

}

Share Improve this question asked Nov 14, 2024 at 15:04 BillBill 412 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

I worked it out for myself - just add a second code snippet!

I got the following from How to search custom posts by ID in WordPress dashboard on Codexin

/**
 * Add search custom posts by their ID in WordPress dashboard
 *
 */
add_action( 'parse_request', 'cdxn_search_by_id' );
function cdxn_search_by_id( $wp ) {
    global $pagenow;

    if( !is_admin() && 'edit.php' != $pagenow && 'students' !== $_GET['post_type']) {
        return;
    }
        
    // If it's not a search return
    if( !isset( $wp->query_vars['s'] ) ) {
        return;
    }
        
    // Validate the numeric value
    $id = absint( substr( $wp->query_vars['s'], 0 ) );
    if( !$id ) {
        return; 
    }
        
    unset( $wp->query_vars['s'] );
    $wp->query_vars['p'] = $id;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736270669a1446.html

最新回复(0)