Using ACF values in a WordPress Search Query

WordPress search by default is kind of limited.

If you use Advanced Custom Forms, the default search does not allow you search through the custom fields.

But, there is a powerful query called wp_query for WordPress that will allow you to do some really custom search scripts.

Here is some code that will query the custom fields in ACF. I have it set to pull a variable from the search form but to get that to work you will need to create a filter and a function on the themes function.php to pass the input result into the search script.

***********************

// args

$args = array(

‘numberposts’ => -1,

‘post_type’ => ‘post’,

‘meta_key’ => ‘bg_certificate’,

‘meta_value’ => $_POST[‘cert’]

);

 

// get results

// get results

$the_query = new WP_Query( $args );

 

// The Loop

?>

<?php if( $the_query->have_posts() ): ?>

<ul>

<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<li>

<a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a>

</li>

<?php endwhile; ?>

</ul>

<?php endif; ?>

 

<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>

******************************

 

Together with the filter and function, this script will output the search results based on the customs field you select in ACF.

You can find lots of other examples on the ACF site.

In my next post, I’ll show how to set up the filter and function to pass the value into the  ‘meta_value’ => $_POST[‘cert’] field.

Comments are closed.