Display "Related Posts" based on ACF Relationship Field - php

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;

Related

filter posts query by post object value

I have a custom post type with a post object field that enables the selection of related pages for the custom post type, the post object field is enabled for multiple posts, and is set to return post id.
I want to build a query in a specific page that checks all the custom post types that are related to this page with post object.
I am using this query:
$val = get_the_ID(); // get current page ID
$args = array(
'post_type' => 'articles_content', //custom post type
'posts_per_page' => -1,
'meta_query' => array(
'key' => 'pages_link', //the name of the post object field
'value' => $val, //the value of the current ID
'compare' => 'LIKE'
),
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ):
while( $the_query->have_posts() ) :
$the_query->the_post();
// Do something...
endwhile;
endif;
wp_reset_query();
The problem is this - for examlpe if my page ID is "80", then the query also brings custom posts that are have pages with ID of "8002" or something similar.
I tried to use the "=" sign in the compare but got no results at all.
How can I query only by the custom posts that have the exact page ID as the current page in their post object array values?
This is the solution if anyone encounters the same issue:
$args = array(
'posts_per_page' => -1,
'post_type' => 'articles_content',
'meta_query' => array(
array(
'key' => 'pages_link',
'value' => '"' . get_the_ID() . '"',
'compare' => 'LIKE'
)
)
);

Display how many reviews there are for a CPT

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();
?>

Wordpress posts count with comman tags within specific category

i have two categories 'A' and 'B'. Both have 5 posts(each) with tag 'C'. How i can display the number of posts as 5 in Category 'A' or 'B' page. It showing total number of post with tag 'C' as 10. I need to show it as 5. How i can pass category variable to display exact count with tag within specific category. Here is my current code:
$tag = get_term_by('name', $tags,'post_tag');
$count = $tag->count;
reference: https://codex.wordpress.org/Function_Reference/get_term_by
This is not possible with the get_term_by() method.
Try this:
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND', // only posts that have both taxonomies will return.
array(
'taxonomy' => 'post_tag',
'field' => 'name',
'terms' => 'TAG_C', // you can also use an array with tags.
),
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'CATEGORY_B', // you can also use an array with categories.
),
),
);
$posts = get_posts($args);
$count = count($posts);
I haven't tested this code, but it should work. Ofcourse you do have
to set the correct terms.
UPDATE
When dealing with many posts I would create a $wpdb sql query that counts the rows, so only a number is returned and not all the posts. You can find an sql count example here.
You can use "found_posts" property of the WP_Query class object.
$args = array(
'posts_per_page' => 10,
'category_name' => 'aaa', // category slug
'tag' => 'ccc' // tag slug
);
$wp_query = new WP_Query( $args );
echo "Total posts count: ".$wp_query->found_posts;

Query on a ACF repeater field

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();

Use ACF checkbox value array to find "More like this"

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 );

Categories