So from the parent taxonomy view:
Child 1
post
post
post
Child 2
post
post
post
post
Child 3
post
post
post
post
I've scoured the internet for a solution to this, but nothing seems to be working. I'm able to successfully echo the term ID, but when I pass that into the query it returns nothing.
<?php
$terms = get_terms( 'ht_kb_category' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<ul>';
foreach ( $terms as $term ) {
if ($term->parent != 0) {
echo '<li><h1>' . $term->name . '</h1></li>';
$the_query = new WP_Query( array(
'post_type' => 'post',
'tax_query' => array(
array (
'taxonomy' => 'ht_kb_category',
'field' => 'slug',
'terms' => $term->slug,
)
),
) );
while ( $the_query->have_posts() ) :
echo '<p>'. the_title() .'</p>';
endwhile;
/* Restore original Post Data
* NB: Because we are using new WP_Query we aren't stomping on the
* original $wp_query and it does not need to be reset.
*/
wp_reset_postdata();
}
}
echo '</ul>';
} ?>
Finally found the solution after some detective work using the custom taxonomy URL. I was missing the 'post_type' and needed to query 'tag_id' instead of 'term_id'.
<?php $current_term_id = $hkb_current_term_id ?>
<?php
$myposts = get_posts(array(
'showposts' => -1,
'post_type' => 'ht_kb',
'tax_query' => array(
array(
'taxonomy' => 'ht_kb_category',
'field' => 'tag_id',
'terms' => $current_term_id)
))
);
echo '<ul>';
foreach ($myposts as $mypost) { ?>
<li><?php echo $mypost->post_title ?></li>
<?php }
echo '</ul>';
?>
Related
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?
I would like to fetch WooCommerce product on the basis of product category on my page template.
Lets say I have a category mattress. I want to fetch all the products related to that mattress category.
Here is my code:
<?php
// Start the Loop.
while ( have_posts() ) : the_post();
// Include the page content template.
get_template_part( 'content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) {
comments_template();
}
endwhile;
?>
How can I achieve this?
Thanks.
— — ( Update 2 of the August 8th ) — —
Finally a good alternative is to use has_term(); wordpress function to filter all products of some category in an if statement. If you have multiple categories you can embed them in an array using also has_term(); function.
As I have said before below on a comment, I think that your problem is here:
// Include the page content template.
get_template_part( 'content', 'page' );
So I will replace it with some custom code to show you that the condition is working fine:
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$loop = new WP_Query( $args );
// Start the Loop
If($loop->have_posts()){
while ( $loop->have_posts() ) : $loop->the_post();
// Here it is your product category
if ( has_term( 'mattress', 'product_cat', $loop->post ); ) {
// from here I display products thumbnails and name
echo '<div class="woocommerce-product" style="padding:5px; float:left;">';
if (has_post_thumbnail( $product_id )) {
echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog');
} else {
echo '<img src="'.woocommerce_placeholder_img_src().'" alt="Placeholder" width="300px" height="300px" />';
}
echo '<div class="product-name">' . $loop->post->post_name . '</div>';
echo '</div>';
}
endwhile;
}
// If needed
wp_reset_query();
wp_reset_postdata();
?>
It also works without condition: has_term( 'mattress', 'product_cat', $loop->post ); replacing $args array by this one:
$args = array(
'post_type' => 'product',
'posts_per_page' => -1, // you can set here number of post per page
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'mattress '
) )
);
This code is tested and fully functional and it goes on function.php file of your active child theme or theme.
Reference:
Display different custom fields for different categories in WooCommerce
WordPress Function Reference - has_term()
— — ( Update 1 - july 9th ) — —
Or you can also use has_category(); function to filter in an if statement this way:
<?php
global $post;
// Start the Loop
while ( have_posts() ) : the_post();
if ( has_category( 'mattress', $post ); ) {
// Include the page content template.
get_template_part( 'content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) {
comments_template();
}
}
endwhile;
?>
You could try this:
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => -1, // you can set here number of post per page
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'mattress '
) )
);
$loop = new WP_Query($args);
If($loop->have_posts()){
while($loop->have_posts()) {
$loop->the_post();
// Include the page content template.
get_template_part( 'content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) {
comments_template();
}
}
}
// If needed
wp_reset_query();
wp_reset_postdata();
?>
Below code should work.
<?php
$query = new WP_Query('posts_per_page=5&post_type=product&product_cat=mattress');
If($query->have_posts()){
while($query->have_posts()) {
$query->the_post();
// Your Code
}
}
wp_reset_query();
wp_reset_postdata();
?>
<ul>
<?php
$taxonomy = 'product_cat';
$orderby = 'title';
$show_count = 0;
$pad_counts = 0;
$hierarchical = 1;
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
$category_id = $cat->term_id;?>
<li><?php echo $cat->name;?></li>
<?php }?>
</ul>
I've got Two custom Post Types set up in Wordpress, One being called Products and the other Suppliers. Slugs for these are 'product' and one being 'supplier'.
These two post types share a custom taxonomy called Suppliers which slug is 'supplier-tax'.This then has lots of children which are the different suppliers.
Basically, What I am trying to do is when you are on a single post page for a product, I need to pull in a post for the supplier as well. I thought that the best way to do this with how I have set it up is to select the appropiate supplier from the supplier taxonomy when on the product page. And this then queries and gets post from the 'Supplier' Post ttype with the same selected Taxonomy.
I wrote this query which brings in posts from the taxonomy, however It needs me to tell it which taxonomy and which slug etc to bring in plus it doesnt query the different post type which makes it useless, however it was a start:
<?php
$the_query = new WP_Query( array(
'post_type' => 'product',
'tax_query' => array(
'taxonomy' => 'supplier-tax',
'field' => 'slug',
'terms' => 'supplier_1',
),
) );
while ( $the_query->have_posts() ) :
$the_query->the_post(); ?>
<?php the_title(); ?>
<?php the_post_thumbnail('full'); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
I've tried to adapt and include parts from queries I've fond on previous sources but I can't seem to crack it. This is my attempt at it:
<?php
$terms = wp_get_post_terms( $post->ID, 'supplier-tax' );
if($terms){
$supplier_terms = array();
foreach ($terms as $term){
$supplier_terms[] = $term->slug;
}
$original_query = $wp_query;
$wp_query = null;
$wp_query = new WP_Query( array(
'post_type' => 'supplier',
'tax_query' => array(
array(
'taxonomy' => 'supplier-tax',
'field' => 'slug',
'terms' => $supplier_terms, //the taxonomy terms I'd like to dynamically query
'posts_per_page' => '-1'
),
),
'orderby' => 'title',
'order' => 'ASC'
) );
if ( have_posts() ): ?>
<?php while (have_posts() ) : the_post(); ?>
<?php the_title(); ?>"><?php the_title(); ?>
<?php endwhile; ?>
<?php endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();
}
?>
Has anyone got any ideas on what I'm doing wrong or how I can make this work?
I managed to find a solution to my problem, whilst I don't think it is the cleanest markup, it works and does the job.
<?php
$the_query = new WP_Query( array(
'post_type' => 'product',
'tax_query' => array(
'taxonomy' => 'supplier-tax',
),
) );
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php
$terms = get_the_terms( $post->ID, 'supplier-tax');
foreach ( $terms as $term ) {
$termID[] = $term->term_id;
}
echo $termID[0];
?>
<?php
$my_query2 = new WP_Query( array(
'post_type' => 'supplier',
'tax_query' => array(
'field' => 'slug',
'terms' => '$termID',
),
) ); ?>
<?php while ($my_query2->have_posts()) : $my_query2->the_post(); ?>
<?php the_title(); ?>
<?php the_post_thumbnail('full'); ?>
<?php the_content(); ?>
<?php endwhile; ?>
My pagination is throwing a 404 error when the posts from General -> Reading are smaller than my custom number of posts on my custom taxonomy cities (custom post type city). From what I saw on SO this issue can be fixed usually by using a filter of pre_get_posts, but don't know how to apply it on my case.
I want to mention that in the taxonomy-cities.php I am getting posts of a category of a custom taxonomy of a custom post type.
taxonomy-cities.php
$cat_ID = get_query_var('cities');
$custom_id = get_term_by('slug', $cat_ID, 'cities');
add_filter('posts_orderby', 'edit_posts_orderby');
function edit_posts_orderby($orderby_statement) {
global $aPostsIDs;
$orderby_statement = 'FIELD(ID, '.implode(',',$_SESSION['saved_city_ids']).')';
return $orderby_statement;
}
$offset = ($paged - 1) * $num_city_guides_post;
$args['post_type'] = 'city';
$args['posts_per_page'] = $num_city_guides_post; // 5
$args['orderby'] = $orderby; // rand
$args['order'] = $order; // DESC
$args['paged'] = $paged; // 1
$args['tax_query'] = array(
array(
'taxonomy' => 'cities',
'field' => 'id',
'terms' => array($custom_id->term_id) // 3742
)
);
}
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
// some code here
endwhile;
else: echo 'No Posts';
endif;
wp_reset_postdata();
For archive-city.php I am using this filter in the functions.php and it works fine, but it doesn't get applied to the taxonomy-cities.php so I get 404:
function portfolio_posts_per_page_city( $query ) {
if (array_key_exists('post_type', $query->query_vars)) {
if ( $query->query_vars['post_type'] == 'city' )
$num_city_guides_post = get_option('num_city_post');
if( empty( $num_city_guides_post ) )
$num_city_guides_post = 9;
$query->query_vars['posts_per_page'] = $num_city_guides_post;
return $query;
}
}
if ( !is_admin() ) add_filter( 'pre_get_posts', 'portfolio_posts_per_page_city' );
This is an old question however i recently had the same issue. The following Snippet is in fact the contents of my taxonomy-template.php using the standard WP_Query, example here.
How to properly paginate custom post type taxonomy
The Query
Firstly because it's a taxonomy template, the first line declares $term allowing me to access the term array and therefore the taxonomy id, name url etc.
Secondly i'm setting the term id as a variable to be used in the tax_query parameter. This is used to query my custom post type videos and then get the taxonomy (category) for the loop, stored in $term_id.
The Fix
Because i'm looping through the posts and limiting the results, we effectively need to search for our remaining posts while excluding the previous results and results thereafter. What this means is quite simple:
You must make your custom post types searchable in order for pagination to work:
Important:
'exclude_from_search' => false,
Example taxonomy-template.php
<?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?>
<?php
$term_id = $term->term_id;
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'videos',
'posts_per_page' => 4,
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => $term->taxonomy,
'field' => 'term_id',
'terms' => $term_id
)
)
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<!-- Loop -->
<?php endwhile; ?>
<?php if ($the_query->max_num_pages > 1) : ?>
<?php endif; ?>
<?php else: ?>
<!-- Nothing Found -->
<?php endif; ?>
Maybe u can solve this without filters.
It`s work for pagination my custom posts types
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array( 'post_type' =>'cities', 'posts_per_page' => 0, 'paged' => $paged );
$query = query_posts( $args );
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
//Do wordpress Loop
<?php endwhile; else: include( get_404_template() ); ?>
<?php endif; wp_reset_postdata(); ?>
I had the same problem with my custom post taxonomies pagination. Older posts page was coming with a 404 page not found. This issue is related to WP taxonomy slug so you have to rewrite rules for your custom post type taxonomies like this below:
function generate_taxonomy_rewrite_rules( $wp_rewrite ) {
$rules = array();
$post_types = get_post_types( array( 'public' => true, '_builtin' => false ), 'objects' );
$taxonomies = get_taxonomies( array( 'public' => true, '_builtin' => false ), 'objects' );
foreach ( $post_types as $post_type ) {
$post_type_name = $post_type->name;
$post_type_slug = $post_type->rewrite['slug'];
foreach ( $taxonomies as $taxonomy ) {
if ( $taxonomy->object_type[0] == $post_type_name ) {
$terms = get_categories( array( 'type' => $post_type_name, 'taxonomy' => $taxonomy->name, 'hide_empty' => 0 ) );
foreach ( $terms as $term ) {
$rules[$post_type_slug . '/' . $term->slug . '/?$'] = 'index.php?' . $term->taxonomy . '=' . $term->slug;
$rules[$post_type_slug . '/' . $term->slug . '/page/?([0-9]{1,})/?$'] = 'index.php?' . $term->taxonomy . '=' . $term->slug . '&paged=' . $wp_rewrite->preg_index( 1 );
}
}
}
}
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'generate_taxonomy_rewrite_rules');
This should work for all custom post type taxonomies and if you want to be more specific then you can try updating these two variables like this:
$post_types = get_post_types( array( 'name' => 'city', 'public' => true, '_builtin' => false ), 'objects' );
$taxonomies = get_taxonomies( array( 'name' => 'cities', 'public' => true, '_builtin' => false ), 'objects' );
Finally, just use your default query loop without passing any arguments. Pages will be generated based on General -> Reading.
I need some help here as I've exhausted every place I can trying to find information. This is what I'm trying to do:
I have created a custom Post type in my admin called "Classes"
That works fine, the data works great and it's inputting in the admin.
I want to make a custom template to show this custom post type. However, everything I try it's not displaying properly. I've tried many code variations.
I know someones already done this and has the block of code to display this. This is what I need the code to do:
List All categories in my custom post type 'classes'
List all posts (show all content, not a link or excerpt) inside of each category.
Display it as such (I'm using Jquery Accordion)
the_category()
the_title()
the_content()
========================================================
By the way, Here is the block of code I'm currently using. It does work, but it ONLY shows the posts, all of them. It does not show the category with posts inside of them.
<?php
$type = 'classes';
$args = array (
'post_type' => $type,
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 10,
'ignore_sticky_posts'=> 1
);
$temp = $wp_query; // assign ordinal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
echo '<h3 class="acc1">';
the_title();
echo '</h3>';
echo '<div class="sc"><div class="vs">View Schedule</div>';
the_content();
echo '</div>';
endwhile;
else :
echo '<h2>Not Found</h2>';
get_search_form();
endif;
$wp_query = $temp;
?>
Community, I need you. Please give your feedback!
What you want to do is actually start with a category query. You have to make sure you query all your categories with your custom post type:
Then for each category you would do pretty much what you have above.
$taxonomy = 'classes';
$args = array('hide_empty' => false,);
$terms = get_terms( $taxonomy, $args );
foreach($terms as $val) {
$term_id = $val->term_id;
$term_name = $val->name;
// now do post query
}
You most likely would have to display the category name as a header for your accordion as well.
Here's all the args for get_terms:
http://codex.wordpress.org/Function_Reference/get_terms
For that query you also most likely have to use a Simple Taxonomy Query (search for that on the page).
http://codex.wordpress.org/Class_Reference/WP_Query
By adding this arg to your above query:
'tax_query' =>
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( $term_name )
)
Is that what you were looking for?
There might be a better way to do this but I just had to recently do this and did pretty much what I just outlined here.
I should have been more clear and said to put the posts query within the foreach of the terms query.
Here's the updated answer based on your last reply (I have not tested this).
<?php
$taxonomy = 'classes';
$args = array('hide_empty' => false,);
$terms = get_terms( $taxonomy, $args );
foreach($terms as $val) {
$term_id = $val->term_id;
$term_name = $val->name;
$type = 'classes';
$args = array (
'post_type' => $type,
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 10,
'ignore_sticky_posts'=> 1,
'tax_query' =>
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( $term_name )
)
);
$temp = $wp_query; // assign ordinal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
echo '<h3 class="acc1">';
the_title();
echo '</h3>';
echo '<div class="sc"><div class="vs">View Schedule</div>';
the_content();
echo '</div>';
endwhile;
else :
echo '<h2>Not Found</h2>';
get_search_form();
endif;
$wp_query = $temp;
}
?>