I'm trying to show related videos on my single post template. I've set up a custom taxonomy called 'sub-category' in Posts. I want to get the sub-category of the current post and loop through any posts with the same sub-category, outputting them to the page. Any ideas on the best way of achieving this?
I'm trying to show related videos on my single post template. I've set up a custom taxonomy called 'sub-category' in Posts. I want to get the sub-category of the current post and loop through any posts with the same sub-category, outputting them to the page. Any ideas on the best way of achieving this?
Share Improve this question asked Jul 11, 2019 at 12:23 user108167user108167 11 silver badge4 bronze badges3 Answers
Reset to default 0try with this function
function get_posts_in_taxonomy($post_type, $taxonomy, $term_id, $include_children=false, $limit)
{
$args = [
'post_type' => $post_type,
'posts_per_page' => $limit,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'terms' => $term_id,
'include_children' => $include_children
],
],
// Rest of your arguments
];
$posts = new WP_Query( $args );
if($posts->have_posts()) {
while($posts->have_posts()) {
$posts->the_post();
//code todo here
}
}
} //end func
function get_the_terms( $post, $taxonomy ) {
if ( ! $post = get_post( $post ) ) {
return false;
}
$terms = get_object_term_cache( $post->ID, $taxonomy );
if ( false === $terms ) {
$terms = wp_get_object_terms( $post->ID, $taxonomy );
if ( ! is_wp_error( $terms ) ) {
$term_ids = wp_list_pluck( $terms, 'term_id' );
wp_cache_add( $post->ID, $term_ids, $taxonomy . '_relationships' );
}
}
/**
* Filters the list of terms attached to the given post.
*
* @since 3.1.0
*
* @param WP_Term[]|WP_Error $terms Array of attached terms, or WP_Error on failure.
* @param int $post_id Post ID.
* @param string $taxonomy Name of the taxonomy.
*/
$terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );
if ( empty( $terms ) ) {
return false;
}
return $terms;}
I think I confused myself on this actually, here's how I did it:
$_terms = wp_get_post_terms($post->ID, 'sub-category', array("fields" => "all"));
foreach ($_terms as $term) :
$term_slug = $term->slug;
$_posts = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => 'sub-category',
'field' => 'slug',
'terms' => $term_slug,
),
),
));
if( $_posts->have_posts() ) :
while ( $_posts->have_posts() ) : $_posts->the_post();
//Output
endwhile;
endif;
wp_reset_postdata();
endforeach;
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745328189a4622754.html
评论列表(0条)