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
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
Share Improve this question asked Jun 28, 2020 at 7:18 KevinKevin 1 2- wordpress.stackexchange/questions/369970/… can someone help me I'm new to StackExchange – Shahzad Raza Commented Jun 28, 2020 at 22:07
- anyone can help me with this wordpress.stackexchange/questions/369970/… – Shahzad Raza Commented Jun 29, 2020 at 10:36
1 Answer
Reset to default 0This 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);?>```