WordPress: Get taxnomy terms which also uses a second taxonomy - php

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;

Related

Wordpress get post from tags

(first of all i'm new with php)
i have a wordpress blog where i have written about some ppl and i added their names as tags in a costum taxonomy to avoid multi language field with polylang.
I was looking for a loop that allow to show, for every tag, the title of post where tag exist.
Example => post's name: "what a chef can do?" (tagged Alex P.)
result: -Alex P. "what a chef can do?" 05/10/2020 - "Tomatos in the world" 15/12/2020.
For every person(tag) i have to make an Accordion.
i've started to write code but i'm not looking for a solution and i'm getting lost.
<?php $tag_args = array(
'orderby' => 'title',
'order' => 'ASC'
);
?>
<ul id="Genre-List">
<li>DEFAULT</li>
<?php
$terms = get_terms(
array(
'taxonomy' => 'chef',
'hide_empty' => false,
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Run a loop and print them all
print_r($terms);
foreach ( $terms as $term ) {
?>
<li><a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
<?php echo $term->name; ?>
</a></li>
<?php
}
}
?>
Thanks if anyone can help about this.. im really getting mad.
If you are looking to get all posts which have any custom taxonomy term associated with it, you will need to query posts using a tax_query rather than simply retrieve all of the terms.
// get 'chef' taxonomy
$terms = get_terms([
'taxonomy' => 'chef',
'hide_empty' => false,
]);
// get any posts with one of the 'chef' taxonomy terms associated with it
$query = new WP_Query([
'post_type' => 'post',
'tax_query' => [[
'taxonomy' => 'chef',
'field' => 'term_id',
'terms' => array_column($terms, 'term_id'),
'operator' => 'IN',
]],
]);
// loop and output posts
while ($query->have_posts()) {
$query->the_post();
var_dump(get_the_title());
}

How to get all post categories without custom post type categories?

I am creating a Blog in wordpress.
I have a list of categories:
Technology,
Art,
fashion,
Home,
Lifetime,
Education,
Business,
Religion,
Design and home,
Marketing
In which some of these categories I am using only in Custom Post Type (Technology, Art, Fashion) and others only in Normal Posts (Home, Life, Education, Business, Religion, Design and home, Marketing).
Now I need to get the list of categories that are only being used from normal posts to show them on my blog ().
I tried to do the following but it returns all categories including CPTs:
$categories = get_categories();
foreach($categories as $category) {
echo '<li class="cat-name" . '>' . $category->name . '</li>';
}
I just need to show the categories:
Home, Life, Education, Business, Religion, Design & Home, Marketing.
And exclude those that are being used in CPT.
Please Help!
You need to pass in the arguments and exclude the term_ids or include on the term_ids you want. You can use one of the following: 'exclude', 'exclude_tree', or 'include'.
$args = array(
'taxonomy' => 'category',
'exclude' => array(65,23,98,23,78), // term_ids you want to exclude
'exclude_tree' => (65,23,98,23,78), // term_ids you want to exclude and their descendants/children
'include' => (11,51,90,57,29), // only the term_ids you want to include
'orderby' => 'name',
'order' => 'ASC',
"hide_empty" => 1,
);
$cats = get_categories($args);
foreach ($cats as $cat){
echo $cat_slug = $cat->slug;
}
'include'
Array or comma/space-separated string of term IDs to include. Default empty array.
'exclude'
Array or comma/space-separated string of term IDs to exclude. If $include is non-empty, $exclude is ignored. Default empty array.
'exclude_tree'
Array or comma/space-separated string of term IDs to exclude along with all of their descendant terms. If $include is non-empty, $exclude_tree is ignored. Default empty array.
Learn more about all the arguments you can pass to get_categories() or get_terms(), get_posts() etc
https://developer.wordpress.org/reference/classes/wp_term_query/__construct/
Try WP_Query if the above isn't working
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'home', 'life', 'education', 'business', 'religion', 'design-and-home', 'marketing' ),
'operator' => 'IN'
),
array(
'taxonomy' => 'custom_taxonomy_registerd_to_cpt_slug', // again make sure in your cpt plugin that this taxonomy is unique and not just 'category'
'field' => 'slug',
'terms' => array( 'technology', 'art', 'fashion' ),
'include_children' => false,
'operator' => 'NOT IN'
)
)
);
$cats = new WP_Query($args);
foreach ($cats as $cat){
print_r($cat); // use this to find the values you need. Remove after you build the link html
}
This function with shortcode is tested and work for me
<?php
function list_categories_func($atts) {
$a = shortcode_atts( array('' => '',), $atts );
$args = array('taxonomy'=>'category','parent'=>0,'orderby'=>'name','order'=>'ASC', 'hide_empty'=>0,);
$categories=get_categories($args);
echo "<ul>";
foreach($categories as $category){
$name=$category->slug;
echo "<li>$id</li>";
}
echo "</ul>";
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode( 'ni_categories_row', 'list_categories_func' );
?>

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

Custom post type - related products

I've made a custom post type "product" on my Wordpress site. The detail page of a product is single-product.php which shows everything about the product perfectly.
All the product will be categorized in the following structure:
Toegangscontroles
Elektronische sloten
Wandlezers
Software
...
Overige producten
Sleutelkaarten
Kluizen
...
I have two test products on my website. Both products have the category "Electronische sloten". Which is a child category of "Toegangscontroles".
I want to show related products on single-product.php This related product cannot be the current product itself and must be under the same parent category. So in this case, a product with child category "Toegangscontroles" must show 5 random related products from the child categories from parent "Toegangscontroles".
This is my code now:
<?php
$related = get_posts( array(
'post_type' => 'product',
'category__in' => wp_get_post_categories($post->ID),
'numberposts' => 5,
'post__not_in' => array($post->ID) ) );
if( $related ) foreach( $related as $post ) {
setup_postdata($post); ?>
<?php the_title(); ?>
<?php }
wp_reset_postdata();
?>
When I go the product A, I see product B under related products, but when I go the the product B page, I don't see product A. Tough they have exactly the same category.
Thanks in advance.
Haven't tested this, but you can try
$related = get_posts( array(
'post_type' => 'product',
'tax_query' => array( array(
'taxonomy' => $taxonomy_name,
'field' => 'term_id',
'terms' => wp_get_post_terms($post->ID, $taxonomy_name, array('fields' => 'ids'))
) ),
'numberposts' => 5,
'exclude' => array($post->ID)
) );
Please use below code i think it will work.
$related = new WP_Query(
array(
'category__in' => wp_get_post_categories( $post->ID ),
'posts_per_page' => 5,
'post__not_in' => array( $post->ID )
)
);
if( $related->have_posts() ) {
while( $related->have_posts() ) {
$related->the_post(); ?>
<?php the_title(); ?>
<?php }
wp_reset_postdata();
} ?>

related post by taxonomy custom plugin developement issue

I am facing issue with a custom plugin, which will show related post by taxonomy from a particular category(mobile). If there are no post matching taxonomy, it should display other posts from that particular category. First I fetched all taxonomies and terms for the current post(single.php). Then I prepare a query argument using loop. The code works for the below cases,
a) I have not added any post tag(current post), then it's showing other posts from the same category(mobile),
b) If I have added a post tag, and there are other post matching the terms of that post tag.
But, it's don't work when I have added a post tag, and there are no post matching those terms. But, here I want, if there are no matching post by the terms, then just display other posts irrespective of terms. I can do this, using a new query when have_posts fails, but I am thinking if there are any other way to do this withing the same query args, please help
I am placing the code which I am trying to develop.
$post_args = array();
$taxonomies = get_post_taxonomies( $post );
foreach ($taxonomies as $key => $taxonomy) {
# code...
if($taxonomy == 'category') continue;
$terms = wp_get_post_terms( get_the_ID(), $taxonomy );
$term_array = array();
if($terms){
foreach ($terms as $key => $value) {
array_push($term_array, $value->slug);
}
array_push($post_args,
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term_array,
)
);
}
}
$tax_query = array();
$tax_query['relation'] = 'OR';
foreach ($post_args as $key => $value) {
# code...
array_push($tax_query, $value);
}
$args = array(
'post_type' => 'post',
// 'category_name' => 'mobiles',
'post__not_in' => array($curr_post_id),
'posts_per_page' => 10,
'orderby' => 'relevance',
'order' => 'ASC',
'tax_query' =>
array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'mobiles',
)
,
array($tax_query)
)
);
$the_query = new WP_Query( $args );
After trying a lot, I just decided to use another post loop. Say, if there are no result from first loop, just select random post from the category. If there are few posts(Max 10 posts) from the first loop, then user another loop to select random posts excluding the post ids we get from first loop.

Categories