0

I want to create an autocomplete AJAX search and I'm trying to have it where when the user starts typing, the list populates titles matching that search string.

My issue is in the WP_query, because I want to search the title, content and search meta key values and show the results. I will be searching the rfi_antenna_sku meta key and alive_antenna_sku meta key, etc for the product post type.

My Query:

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

    $args = array(
        'posts_per_page' => -1,
        's' => esc_attr( $_POST['keyword'] ),
        'post_type' => array('product'), 
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => 'rfi_antenna_sku',
                'value' => esc_attr( $_POST['keyword'] ),
                'compare' => 'LIKE',
            ),
            array(
                'key' => 'alive_antenna_sku',
                'value' => esc_attr( $_POST['keyword'] ),
                'compare' => 'LIKE',
            )
        )
    );

    $the_query = new WP_Query( $args );
    if( $the_query->have_posts() ) :
        echo '<ul>';
        while( $the_query->have_posts() ): $the_query->the_post(); ?>

            <li><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></li>

        <?php endwhile;
       echo '</ul>';
        wp_reset_postdata();  
    endif;

    die();
}

In case it helps future people, here's the rest:

function antennas_competitive_search_form() {
 $output = '<div class="search_bar">';
    $output .= '<form action="/" method="get" autocomplete="off">';
        $output .= '<input type="text" name="s" placeholder="Search Code..." id="keyword" class="input_search" onkeyup="fetch()">';
        $output .= '<button>';
            $output .= 'Search';
        $output .= '</button>';
    $output .= '</form>';
    $output .= '<div class="search_result" id="datafetch">';
        $output .= '<ul>';
            $output .= '<li>Please wait..</li>';
        $output .= '</ul>';
    $output .= '</div>';
 $output .= '</div>';

 return $output;
}


/**
 * Ajax Search
 */
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){

    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });

}
</script>

<?php
}

And lastly, the links I've researched before posting here:

WP_Query with meta_value LIKE 'something%'

Get posts by meta value

How to search for meta_query LIKE or tax_query LIKE and grab these posts on search results?

Using meta query ('meta_query') with a search query ('s')

4
  • The last link have various options/code that you can choose from, so have you tried any of that? Or what have you tried and what didn't work as expected? Do you want the meta query to be used only if a search keyword is specified, i.e. "no search, no meta query"?
    – Sally CJ
    Commented Feb 26, 2023 at 6:16
  • I saw that, and I did try this answer: wordpress.stackexchange.com/a/208939/20663 but it still didn't work. When I tried typing any of the values I had stored as a value in one of the custom fields it didn't pull up and response data was empty.
    – Derek
    Commented Feb 26, 2023 at 23:13
  • 1
    I wrote an answer to a similar question in January 2022, so you can use the same trick/workaround there, but in your case, you don't need to hook on pre_get_posts and simply add '_search_OR' => true to your $args array. Another option is of course to manually construct your ( <search query> OR <meta query> ) during the posts_search hook, but you will need to handle matters such as table joining and aliasing, and writing the SQL which searches in your metadata, on your own.
    – Sally CJ
    Commented Feb 27, 2023 at 4:09
  • 1
    Also, you should instead set the posts_per_page to a reasonable high number which the database can handle at a time, e.g. 100 or 50, and if there are more posts, then use the paged arg to paginate your query. You should also ensure that $_POST['keyword'] is not empty or has a non-zero length before adding your meta query.. and use wp_die() instead of die(). You should also use get_permalink() instead of post_permalink() which has long been deprecated.
    – Sally CJ
    Commented Feb 27, 2023 at 4:43

0

Your Answer

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