0

Is it possible to write a query to search for data from one custom field only? I have a CPT called 'lectures' and I only want to search for data that is in the custom field called 'keywords' I have this:

<?php
        $args = array(
            'post_type' => 'lectures',
            'order' => 'ASC',
            'posts_per_page' => -1,
            'meta_key' => 'keywords'
            
        );
        $query = new WP_Query($args);
        while ( $query -> have_posts()) : $query -> the_post();

    ?>

but it is not working. So if someone searches for 'Operant Conditioning' (one of the terms in the keywords ACF). I want any CPT with those 'keywords' (from the ACF) to show in results. I cannot add a specific keyword as there will be hundreds

2

1 Answer 1

0

This worked for me:

<?php
 if($_GET['module_search'] && !empty($_GET['module_search']))
     $keywords = $_GET['module_search'];
?>

<!-- Set args for search of cpt -->
            <?php
                $args = array(
                    'post_type' => 'lectures',
                    'order' => 'ASC',
                    'posts_per_page' => -1,
                    'meta_query' => array(
                      'relation' => 'OR',
                         array( 
                         'key' => 'keywords', // name of custom field
                         'value' => '[[:<:]]'.$keywords.'[[:>:]]', // matches exaclty "123", not just 123. This prevents a match for "1234"
                         'compare' => 'REGEXP'
        )
    )
                    
                );
                $query = new WP_Query($args);?>```

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.