admin管理员组文章数量:1394156
I want to show related posts of my child taxonomy term from taxonomy terms of custom post type.
CPT: project
Taxonomy name: preferences
Parent term: 2BHK, 3 BHK
Child term of 2 BHK: completed projects, under construction
Child term of 3 BHK: same as 2 BHk with different slug
I am getting related posts of 2 BHK from parent term but not getting child terms posts i.e under construction.
This is my effort:
function in functions.php
function get_related_posts( $taxonomy = '', $args = array() )
{
/*
* Before we do anything and waste unnecessary time and resources, first check if we are on a single post page
* If not, bail early and return false
*/
if ( !is_single() )
return false;
/*
* Check if we have a valid taxonomy and also if the taxonomy exists to avoid bugs further down.
* Return false if taxonomy is invalid or does not exist
*/
if ( !$taxonomy )
return false;
$taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
if ( !taxonomy_exists( $taxonomy ) )
return false;
/*
* We have made it to here, so we should start getting our stuff togther.
* Get the current post object to start of
*/
$current_post = get_queried_object();
/*
* Get the post terms, just the ids
*/
$terms = wp_get_post_terms( $current_post->ID, $taxonomy, array( 'fields' => 'ids') );
/*
* Lets only continue if we actually have post terms and if we don't have an WP_Error object. If not, return false
*/
if ( !$terms || is_wp_error( $terms ) )
return false;
/*
* Set the default query arguments
*/
$defaults = array(
'post_type' => $current_post->post_type,
'post__not_in' => array( $current_post->ID),
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'terms' => $terms,
'include_children' => false,
),
),
);
/*
* Validate and merge the defaults with the user passed arguments
*/
if ( is_array( $args ) ) {
$args = wp_parse_args( $args, $defaults );
} else {
$args = $defaults;
}
/*
* Now we can query our related posts and return them
*/
$q = get_posts( $args );
return $q;
}
single-custom_post_type.php
<div class="row">
<?php
if ( function_exists( 'get_related_posts' ) ) {
$related_posts = get_related_posts( 'preferences', array( 'posts_per_page' => -1) );
if ( $related_posts ) {
foreach ( $related_posts as $post ) {
setup_postdata( $post ); ?>
<div class="col-md-3">
<?php the_post_thumbnail(); ?>
<h4> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </h4>
</div>
<?php
}
wp_reset_postdata();
}
}
?>
</div>
本文标签: Get related posts of child term of custom post type
版权声明:本文标题:Get related posts of child term of custom post type 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744739468a2622523.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论