Support

Account

Home Forums ACF PRO Search in post object field by post_id Reply To: Search in post object field by post_id

  • Thanks @peterseb for this solution. Worked for me, on a Post Object field. In my case I needed users (admins actually) to be able to search for a post by its ID. Here’s my code for that:

    function cf_post_object_query( $args ) {
        // Set a query variable to identify the post object query
        $args['is_acf_query'] = true;
        // return
        return $args;
    }
    // filter for a specific field
    add_filter('acf/fields/post_object/query', 'cf_post_object_query');
    
    function cf_search_where( $where, $wp_query ) {
        global $pagenow, $wpdb;
        $is_acf = isset( $wp_query->query['is_acf_query'] ) ? $wp_query->query['is_acf_query'] : false;
        if ( is_search() || $is_acf ) {
            $where = preg_replace(
                "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
                //"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
                "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->posts.".ID LIKE $1)", $where );
        }
        return $where;
    }
    add_filter( 'posts_where', 'cf_search_where', 10, 2 );