Display how many reviews there are for a CPT - php

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

Related

Showing list of posts including custom taxonomy terms

I'm working on a WP_Query loop that is suppose to show the list of posts in a following way
+ Custom taxonomy term 1
++ Post 1
++ Post 2
+ Custom taxonomy term 2
++ Post 1
++ Post 2
So in general it will work for CPT called 'career'. In a real life my custom taxonomy (job-category) is like: Drivers, Logistics, HR etc. And to each of such taxonomy/category I've got created specific posts. There is also a custom taxonomy called job-country which suggests the territory.
To achieve the way of showing my posts I am using the following code:
<?php
$terms = get_terms([
'taxonomy' => 'job-category',
'hide_empty' => true,
'orderby' => 'count',
'order' => 'DESC'
]);
usort( $terms, function( $a, $b ) {
$a_ste = (int) get_term_meta( $a->term_id, 'stick_to_end', true );
$b_ste = (int) get_term_meta( $b->term_id, 'stick_to_end', true );
if ($a_ste == $b_ste) return 0;
return ($a_ste < $b_ste) ? -1 : 1;
} );
if ($terms) { //categories exists
foreach ($terms as $category) { ?>
<h2 class="category-title">
<?= $category->name ?>
</h2>
<?php
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'career',
'tax_query' => [
[
'taxonomy' => 'job-category',
'field' => 'term_id',
'terms' => $category->term_id,
]
]
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'JobListThumb.php';
};
wp_reset_postdata();
}
}
} else { //no categories
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'career'
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'JobListThumb.php';
};
wp_reset_postdata();
}
}
?>
And it works. But because of certain reasons (working on an ajax filtering function) I need to achieve the same thing using traditional wp_query.
This is what I've got:
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_type' => 'career',
);
// for taxonomies / categories
if( isset( $_POST['categoryfilter'] ) && isset( $_POST['taxonomyfilter'] ))
$args['tax_query'] = array(
'relation' => 'AND',
array(
'taxonomy' => 'job-category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
),
array(
'taxonomy' => 'job-country',
'field' => 'id',
'terms' => $_POST['taxonomyfilter']
)
);
// if you want to use multiple checkboxes, just duplicate the above 5 lines for each checkbox
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
But I've stucked in a place - how to add those terms / elements to the query? Obviously cannot mix get_terms with wpquery by simply copying instead echo'ing the title.
Do you have any suggestions how to solve this?

WordPress: Get taxnomy terms which also uses a second taxonomy

Let's say I have a website which sells cars.
I'm using a custom taxonomy called brand for the manufacturer (like BMW, Audi, ...) and a custom taxonomy called type for the type of cars (like SUV, Coupe, ...).
For the cars itself I'm using a custom post type called models.
Now I want to show every car brand in the taxonomy archive for type (All brands with SUVs).
To do that, I'm trying to get all brands and filter them with all types.
As result there should be a list with all car brands that have SUVs.
Here's my current code to get a list of brands:
$taxonomies = get_terms( array(
'taxonomy' => 'brand',
'hide_empty' => false
) );
if ( !empty($taxonomies) ) :
$output = '<select>';
foreach( $taxonomies as $category ) {
if( $category->parent == 0 ) {
$output.= '<optgroup label="'. esc_attr( $category->name ) .'"></optgroup>';
}
}
$output.='</select>';
echo $output;
endif;
I couldn't find a way to add a second taxonomy to this snippet.
Is this the wrong approach?
Maybe I need to get the custom post types (models) first to check which one has both terms?
This article has a really helpful breakdown.
I needed to get the taxonomies that were part of another taxonomy for use in creating a dropdown (and some other uses.) This code allowed me to identify the "categories" that were part of a particular "destination".
$dest_slug = get_query_var('term');
$desination_ids = get_posts(array(
'post_type' => 'item',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'destinations',
'field' => 'slug',
'terms' => $dest_slug
)
),
'fields' => 'ids'
));
$categories = wp_get_object_terms($desination_ids, 'category');
I found a solution that works:
$productcat_id = get_queried_object_id();
$args = array(
'numberposts' => -1,
'post_type' => array('models'),
'tax_query' => array(
array(
'taxonomy' => 'brand',
'field' => 'term_id',
'terms' => $productcat_id,
),
),
);
$cat_posts = get_posts($args);
$my_post_ids = wp_list_pluck ($cat_posts, 'ID');
$my_terms = wp_get_object_terms ($my_post_ids, 'types');
if ( !empty($my_terms)) :
echo '<ul>';
foreach( $my_terms as $my_term ):
$brand_name = $my_term->name;
$brand_link = get_term_link($my_term);
echo '<li><a alt="'.$brand_name.'" href="'.esc_url( $brand_link ).'">'.$brand_name.'</a></li>';
endforeach;
echo '</ul>';
endif;

How to display posts of taxonomy in WordPress page template?

Not sure if this has been asked before, but I'm a bit lost. I've created a "Newsroom" Pods with a custom taxonomy of Newsroom Category. Newsroom Category has 3 fields: Press Release, Media, Others. I have a WordPress page template: taxonomy-newsroom_category.php
taxonomy-newsroom_category.php is used to display Pods posts if meets the following:
1 - pods = 'newsroom'
2 - taxonomy = 'press_release' || 'media' || 'others'
My issue right now is that I can't find a way to display the post details:
image(thumbnail), title(post title), date_published
I hope someone can help. Thanks
Here's the code I'm currently using:
<?php
//Setup Pod object
//Presuming permalink structure of example.com/pod-name/item-name
//See http://pods.io/code/pods/find
//Set $params to get 5 items
$params = array(
'limit' => 5,
);
//get current pod name
$pod_name = pods_v( 0, 'newsroom');
//get pods object
$pods = pods( $pod_name, $params );
//check that total values (given limit) returned is greater than zero
if ( $pods->total() > 0 ) {
//loop through items using pods::fetch
while ($pods->fetch() ) {
//Put title/ permalink into variables
$post_title = $pods->display('post_title');
$date_published = $pods->display('date_published');
$permalink = site_url( trailingslashit( $pod_name ) . $pods->field('permalink') );
?>
<div class="news-item col-sm-4">
<div class="news-item-img"></div>
<div class="news-item-header">
<h5 class="news-category"></h5>
<h2 class="news-item-title"><?php echo $post_title; ?></h2>
<h5 class="news-item-date"><?php echo $date_published; ?></h5>
</div>
</div><!-- close -->
<?php
} //endwhile;
} //endif;
// Output Pagination
//see http://pods.io/docs/code/pods/pagination
echo $pods->pagination( );
?>
I also found out solution for that... I had my Custom Post Type "studies" and I had to filter them, based on custom taxonomy category. If you want to write Posts of one taxonomy category, try to use something like that:
$type = $_GET['type'];
$args = array(
"post_type" => "studien",
"post_per_page" => -1,
"relation" => "AND"
);
if($type != "") {
$args['tax_query'][] = array(
'taxonomy' => 'market',
'field' => 'slug',
'terms' => $type
);
$wp_query = new WP_Query($args);
}
$type represents one category in my created Taxonomy (value comes from HTML code in select option), $args Is some query on database and 'market' is slug of my custom Taxonomy, $wp_query returns all filter Posts
screenshot of my custom taxonomy in custom post type. As you can see, I have two groups. First is clicked in two Posts and Second is clicked in last two Posts. Maybe it will helps you to give imagination
Check this out https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters. This document explained how to query with custom post type and taxonomy in details. Youd code could be something like this.
$args = array(
'post_type' => 'newsroom',
'tax_query' => array(
array(
'taxonomy' => 'newsroom_category',
'field' => 'slug',
'terms' => 'press_release',
),
),
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$id = get_the_ID(); // with post id, you can get whatever you want.
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
from the wordpress documenation:
https://codex.wordpress.org/Custom_Taxonomies
we have the below , for taxonomy person
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'person',
'field' => 'slug',
'terms' => 'bob'
)
)
);
$query = new WP_Query( $args );

Limit Woocommerce featured products in a WP_Query

I want to get 3 featured products in the header of the site. But my query keeps returning unlimited number of results.
I've been looking online for a solution and came across answers that all answer saying the same thing in terms of the query. What could I be doing wrong?
$meta_query = WC()->query->get_meta_query();
$tax_query = WC()->query->get_tax_query();
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN',
);
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 2,
'meta_query' => $meta_query,
'tax_query' => $tax_query,
);
$featured_query = new WP_Query( $args );
if ($featured_query->have_posts()) {
while ($featured_query->have_posts()) :
$featured_query->the_post();
$product = get_product( $featured_query->post->ID );
echo $product->title; echo "test";
// Product info here
endwhile;
}
wp_reset_query();
The following query returned 20 results. The code was placed in header.php. Using woocommerce 3.x.
First your code is a bit outdated, since Woocommerce 3, as get_product() need to be replaced with wc_get_product() and $product->title; by $product->get_title();…
Once done your code works and you will get 3 featured products:
$meta_query = WC()->query->get_meta_query();
$tax_query = WC()->query->get_tax_query();
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN',
);
$featured = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 3, // <== <== <== 3 products
'meta_query' => $meta_query,
'tax_query' => $tax_query,
) );
// Get the products count in the query
echo '<p>Featured products count: ' .$featured->post_count . '</p>';
if ($featured->have_posts()) : while ($featured->have_posts()) :
$featured->the_post();
$product = wc_get_product( $featured->post->ID );
echo $product->get_title() . '<br>';
// Product info here
endwhile; endif;
wp_reset_postdata();
It should work for you as I have tested successfully this code on header.php file…
As before Woocommerce 3, the "featured products" where handled by post meta data (a meta query), you may need to update product terms count going to Woocommerce settings > status > tools. In "Term counts" section click on "Recount terms".
You should be using wp_reset_postdata() instead of wp_reset_query() since WP_query doesn't overwrite the main query.
If that doesn't solve your issue, make sure any other custom loops use the appropriate reset, and/or try renaming the variable $featured_query if you're using it elsewhere - it may be inheriting posts from a previous loop.
You could also try adding the 'nopaging' => true and 'ignore_sticky_posts' => true arguments
I hate to suggest it, but if you can't figure out why it's returning 20 posts instead of 2, you could just break your while loop with a counter:
if ($featured_query->have_posts()) {
$counter = 0;
while ($featured_query->have_posts()) : $featured_query->the_post();
/* Do post stuff here */
$counter++;
if( $counter == 2 ) break;
endwhile;
}

Display "Related Posts" based on ACF Relationship Field

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;

Categories