I would like to query an ACF repeater field. I've a repeater field called Library (in a CPT called Book) and, in this repeater, I have a relation field called Library (that is connected to an other custom post type called Library). It is this field that I would like to query*.
I look to recover, thanks to an unique value given by the user (selected thanks to a select), all the books that are in relation with this Library.
Ex : 'Library 1' is selected. Return : 'Harry Potter 1' and 'Harry Potter 2'.
Trials (not working)
function my_posts_where( $where ) {
$where = str_replace("meta_key = 'library_$", "meta_key LIKE 'library_%", $where);
return $where; } add_filter('posts_where', 'my_posts_where');
$library= $_GET['library'];
$v_args = array(
'post_type' => 'book',
'meta_query' => array(
array(
'key' => 'library_$_library',
'compare' => '=',
'value' => $library,
),
)
); $Query = new WP_Query($v_args);
if($Query->have_posts()) :
while($Query->have_posts()) : $Query->the_post();
...
endwhile;
else :
...
endif;
And this
$library= $_GET['library'];
$v_args = array(
'post_type' => 'book',
'meta_query' => array(
array(
'key' => 'library',
'value' => $library,
'compare' => 'LIKE',
),
)
);
$Query = new WP_Query($v_args);
I searched on the Internet, I could not resolve my problem ...
Thanks a lot.
-* : I also have a repeater field called Tags and in it a Taxonomy field in relation with tags. I would like to show all the books that have thig tag.
This is a bit late, but in case this helps anyone else, this works for me:
//Since the changed behaviour of esc_sql() in WordPress 4.8.3,
//cannot use the % character as a placeholder, hence need to alter 'where' close:
function my_posts_where( $where ) {
$where = str_replace("meta_key = 'library_$", "meta_key LIKE 'library_%", $where);
return $where;
}
add_filter('posts_where', 'my_posts_where');
$library_id = $_GET['library']; //get querystr var
$args = array(
'post_type' => 'book',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'library_$_library', // our repeater field post object
'value' => '"'. $library_id .'"', //matches exactly "123", not just 123 - prevents a match for "1234"
'compare' => 'LIKE'
)
)
);
$query = new WP_Query($args);
if ($query->have_posts()):
while ($query->have_posts()) : $query->the_post();
echo $post->post_title.'<br>';
endwhile;
endif;
wp_reset_query();
Related
How do I query related product post title instead of the whole post object array in my WordPress query below?
$product_search = $_GET['s'];
$related_product = get_field( 'related_products' ); // This is an ACF relationship field so I can link products to articles and display teh related article in search.php from the product page
$knowledge_args = array(
'post_type' => 'knowledge_hub',
'fields' => 'ids',
'posts_per_page' => -1,
'meta_query' => array(
'key' => $related_product, // How do I query related product post title instead of whole post object array?
'value' => $product_search,
'compare' => 'LIKE'
)
);
$relatedProductArticles = new WP_Query($knowledge_args);
You could do that by manipulating the sql "WHERE" clause.
Create a custom function that does the filtering for you!
Add the argument that our custom function is looking for
Add the filter right before the custom WP_Query
Remove the filter after WP_Query
So you could write a the custom function in your functions.php like so:
function related_products_title_filter($where, $wp_query)
{
global $wpdb;
if ($searched_term = $wp_query->get('my_custom_search_filter_title')) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql(like_escape($searched_term)) . '%\'';
}
return $where;
}
Add a custom argument to the arguments:
$knowledge_args = array(
'my_custom_search_filter_title' => $product_search, // This is the custom argument that our function is looking for
'post_type' => 'knowledge_hub',
'fields' => 'ids',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => $related_product,
'value' => $product_search,
'compare' => 'LIKE'
)
)
);
Add the filter right before the custom WP_Query:
add_filter('posts_where', 'related_products_title_filter', 10, 2);
Remove the filter after WP_Query
remove_filter('posts_where', 'related_products_title_filter', 10, 2);
So your entire code would be something like this:
function related_products_title_filter($where, $wp_query)
{
global $wpdb;
if ($searched_term = $wp_query->get('my_custom_search_filter_title')) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql(like_escape($searched_term)) . '%\'';
}
return $where;
}
$product_search = sanitize_text_field($_GET['s']);
$related_product = get_field( 'related_products' );
$knowledge_args = array(
'my_custom_search_filter_title' => $product_search,
'post_type' => 'knowledge_hub',
'fields' => 'ids',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => $related_product,
'value' => $product_search,
'compare' => 'LIKE'
)
)
);
add_filter('posts_where', 'related_products_title_filter', 10, 2);
$relatedProductArticles = new WP_Query($knowledge_args);
remove_filter('posts_where', 'related_products_title_filter', 10, 2);
Let me know if you were able to get it to work!
I have two custom post types, 'product' and 'product_review'. The CPT 'product_review' has a taxonomy 'product_name' whose slug matches the CPT 'product'
An example 'Product A' is the product post. 'Product Review A' is the product_review post that has a 'product_name' taxonomy value of 'product_a'.
I need to show how many 'product_review' each 'product' has.
<?php
global $post;
$post_slug = $post->post_name;
//echo $post_slug;
//this outputs the name of the product, which I need
$terms = get_terms('product_review');
foreach ( $terms as $post_slug ) {
echo $term->count . 'Reviews';
?>
It doesn't show any count. I want it to show how many $terms(how many reviews) are tied to $post_slug(name of product). The 'product_review' slug matches the slug of the product.
You can use a custom WP_Query and the found_posts prop like below:
// example query args
$args = [
// look for reviews cpt
'post_type' => 'product_review',
// limit to posts that match our taxonomy product name
'tax_query' => [
[
'taxonomy' => 'product_name',
'field' => 'slug',
'terms' => [ 'product_a' ]
]
]
];
// run the query
$query = new WP_Query( $args );
// grab "total" found posts
$total = $query->found_posts;
// display the total
echo $total
// reset post data so we dont break the main loop
wp_reset_postdata();
#mikerojas answer got me close, but wasn't returning accurate data. Here is what I came up with that got me what I needed.
<?php
$review_args = array(
'post_type' => 'my_post_type',
'post_status' => 'publish',
'tax_query' => array(
array (
'taxonomy' => 'my_taxonomy',
'field' => 'slug',
//this is already inside a loop, making it dynamic to only grab the reviews whose tax value equals the post slut
'terms' => $post->post_name,
)
),
);
if($num = count( get_posts ( $review_args)) <= 1) {
echo 'Review ' . $num = count( get_posts( $review_args ) );
} else {
echo 'Reviews ' . $num = count( get_posts( $review_args ) );
}
wp_reset_postdata();
?>
I am looking for a way to filter my posts by custom fields,
for example this link:
mywebsite.com/?color:red
looks for all the post that has custom field named color and the value red
I will be appreciate it if you can help me, I searched all over internet and I got nothing.
I don't know if it's a typo but the example link you provided will not work. Query format is like this, ?property=value&another_property=another_value.
If your query is mywebsite.com/?color=red you can use the $_GET to get the value from the query and use it for what ever you need.
// check if we have a query property of color and that property has a value
if (isset($_GET['color']) && !empty($_GET['color'])) {
// filter the result and remove any spaces
$color = trim(filter_input(INPUT_GET, 'color', FILTER_SANITIZE_STRING));
// Create the arguments for the get_posts function
$args = [
'posts_per_page' => -1, // or how many you need
'post_type' => 'YOUR_POST_TYPE', // if the post type is 'post' you don't need this line
'post_status' => 'publish', // get only the published posts
'meta_query' => [ // Here we use our $_GET data to find all posts that have the value of red in a meta field named color
[
'key' => 'color',
'value' => $color,
'compare' => '='
]
]
];
$posts = get_posts($args);
}
if (!empty($posts)) {
// Now you can loop $posts and do what ever you want
}
Hope this helps =].
EDIT
Answering your question about getting posts with multiple meta values.
if ((isset($_GET['color']) && !empty($_GET['color'])) && (isset($_GET['size']) && !empty($_GET['size']))) {
// filter the result and remove any spaces
$color = trim(filter_input(INPUT_GET, 'color', FILTER_SANITIZE_STRING));
$size = trim(filter_input(INPUT_GET, 'size', FILTER_SANITIZE_STRING));
// Create the arguments for the get_posts function
$args = [
'posts_per_page' => -1, // or how many you need
'post_type' => 'YOUR_POST_TYPE', // if the post type is 'post' you don't need this line
'post_status' => 'publish', // get only the published posts
'meta_query' => [ // now we are using multiple meta querys, you can use as many as you want
'relation' => 'OR', // Optional, defaults to "AND" (taken from the wordpress codex)
[
'key' => 'color',
'value' => $color,
'compare' => '='
],
[
'key' => 'size',
'value' => $size,
'compare' => '='
]
]
];
$posts = get_posts($args);
}
if (!empty($posts)) {
// Now you can loop $posts and do what ever you want
}
You can use the ACF-fields in a Meta Query like this:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',
'meta_key' => 'color',
'meta_value' => 'red'
));
There are more examples in the ACF documentation:
https://www.advancedcustomfields.com/resources/query-posts-custom-fields/#custom-field%20parameters
I'm using an ACF checkbox to designate categories (called "aims") for Psychology apps/sites. So values would be, say, "Mindfulness", "Well-Being" and "Depression".
Since it's possible to select multiple values, what I'd like to do is have a More Like This where any single post could show other posts that match one or more of the categories of the post.
UPDATE: Here's the code I'm using now, which I'm still not having any luck with:
the_field( 'aims'); /* since I'm on the page for a single post, this gives me the aims for the current post and is currently returning values from the checkbox with multiple selections (as an array, I believe) */
$args = array(
'numberposts' => -1,
'post_type' => 'program',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'aims',
'value' => 'Well-Being', /* I'd actually like this to use the aims for the current post, but I've hard-coded for testing, and am not seeing any results */
'compare' => 'IN')
));
$more_like_this = new WP_Query ($args);
while ($more_like_this->have_posts()) : $more_like_this->the_post();
$star_rating = get_field('overall_score');
?>
<?php the_title(); ?>
<?php echo $star_rating ?>
<?php endwhile;
wp_reset_query();
?>
If you need a wp query to select some posts where multiple ACF checkbox options must be checked you can do like this:
// Get the array with selected options
$fields = get_field('somefield');
// First create the meta_query variable (AND can also be OR)
$meta_query = array('relation' => 'AND');
foreach( $fields as $field ){
$meta_query[] = array(
'key' => 'name_of_acf_checkbox_here',
'value' => $aim,
'compare' => 'LIKE',
);
}
// args
$args = array(
'numberposts' => -1,
'post_type' => 'postype_here',
'meta_query' => $meta_query,
);
$the_query = new WP_Query( $args );
I want to display "Related posts" of a single post page with custom post type named 'property' which is using the ACF Relationship Field for another custom post type.
That other post type is 'contact' and in the Single Properties post type, the relationship field is calling out for that. I have been trying to understand ACF's documentation here, but I was not able to really comprehend why my code isn't working.
I need to show related properties based on the brokers. I don't fully understand SQL statements and table joining.
$properties = get_posts(array(
'post_type' => 'property', // Page Custom Post Type
'posts_per_page' => 6,
'meta_query' => array(
// 'relation' => 'AND',
// array(
'key' => 'contact', // Field name with 2nd custom post type, 'contact'
'value' => '"' . get_the_ID() . '"',
'compare' => 'LIKE'
// )
)
));
Turns out the reason that this was messed up was due to the way ACF stored the array. Their documentation, while it works for their case, was off in mine due to a nester array.
This is what worked for me.
// This is the start of figuring out the array issue
$contact = get_field( 'contact' );
// This showed me the first array
$contact_array = $contact[0];
// This showed me the ACF array and allowed me to return the ID
$contact_ID = $contact_array->ID;
$properties = get_posts(array(
'post_type' => 'property',
'posts_per_page' => 6,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'contact',
// Had to call the value like this as the array was nested like
// a:2:{i:0;s:3:"123";i:1;s:3:"321";} or something.
'value' => '"' . $contact_ID . '"',
'compare' => 'LIKE'
)
)
));
A more complex query with an additional taxonomy called medienform
// Shortcode for ACF - Add Relationship ACF field [sc_acf_fields]
//
add_shortcode( 'sc_acf_fields', 'related_relationship' ); // Add your shortcode here
function related_relationship() {
// get the taxonomy medienform
$cat_taxonomies = get_terms( 'medienform', $args );
$count = count($cat_taxonomies); // wird nicht verwendet
//
/// foreach category as $form_category - medienform
//
foreach ( $cat_taxonomies as $form_category ):
// check the arguments of the post_type, orderby
$args =array(
'posts_per_page' => -1,
'post_type' => 'materialien', // the CPT
'orderby' => 'title', // menu_order
'order' => 'ASC', // DESC
'tax_query' => array( // the tax_query is important to list the posttypes to its taxonomies
'relation' => 'AND',
array(
'taxonomy' => 'medienform',
'field' => 'slug',
'terms' => $form_category->slug
)
),
'meta_query' => array( // the meta_query is important to list only the related posts of the key
array(
'key' => 'post-relationship', // name of custom field Relationship in: https://qualitaetsoffensive-teilhabe.de/wp-admin/post.php?post=12067&action=edit&classic-editor=1
'value' => '"' . get_the_ID() . '"', // matches exactly "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
),
);
//
// make an own WP_Query from the $args
$materials = new WP_Query( $args );
//
// let´s give the category ->name here and the term_link().
// actually a category should only be displayed when it has some child // here we build the accordeon
//
if ($materials->have_posts() ) {
echo '<h4>' . $form_category->name . '</h4>';
};
//
// while schleife
while ( $materials->have_posts() ) {
//
//// use variable as the_post() query
$materials->the_post();
?>
<div class="post-loop-single">
<div class="thumbnail-img"><span><?php the_post_thumbnail('post-thumb'); ?> </span></div>
<div class="post-loop">
<div class="post-loop-title"><?php the_title(); ?></div>
</div>
</div>
<?php } wp_reset_query();
endforeach;