WordPress Custom Post Type and Custom Taxonomy

I am having a problem with custom post type and custom taxonomies. I created a custom post type called ‘galleries’ and taxonomies named ‘gallery_type’. And I have created a page called Gallery in which i loaded all the posts from galleries. And then I have created ‘garden’ & ‘house’ taxonomy terms and assigned 3-3 posts to each ‘garden’ & ‘house’. And I linked the taxonomy terms ‘garden’ and ‘house’ as sub-menu to gallery which is my current parent. I want to display the posts in their respective terms. But it is not loading. What can I do ??
My code is: ‘

$tax = 'gallery_type';
$terms = get_the_terms($post->ID, $tax);
if($terms){
foreach($terms as $term){
$single = $term->name;
?>

    <?php
    $args = array('post_type'=>'galleries',
    'posts_per_page'=> -1,
    'tax_query'=>array(
    array('taxonomy'=>'gallery_type',
    'terms'=> $single)
    ),
    'order_by'=>'post_date');
    $query = new WP_Query($args);
    if($query->have_posts()){
    while($query->have_posts()):
    $query->the_post();
    $post_id = $post->ID;
    ?>
    <li class="thumb <?php echo $post_id; ?>" onclick="changeContent(<?php echo $post_id; ?>);">
    <?php if(has_post_thumbnail())
    the_post_thumbnail('gallery-thumb');
    ?>

    <?php
    endwhile;
    wp_reset_query();
    }
    else{
    _e('No image found in gallery');
    }
    '

Any fix???

Related posts

Leave a Reply

1 comment

  1. Try using the slug instead on the name of the taxonomy term.

    $tax = 'gallery_type';
    $terms = get_the_terms($post->ID, $tax);
    if($terms){
    foreach($terms as $term){
    $single = $term->slug;
    
    // Also instead of this query for the taxonomy, as you are on the taxonomy page, you should use $single = $wp_query->query_vars['taxonomy_name']; <- This is the slug of the current viewed taxonomy
    
    ?>
    
        <?php
        $args = array('post_type'=>'galleries',
        'posts_per_page'=> -1,
        'tax_query'=>array(
        array('taxonomy'=>'gallery_type','field' => 'slug',
        'terms'=> $single)
        ),
        'order_by'=>'post_date');
        $query = new WP_Query($args);
        if($query->have_posts()){
        while($query->have_posts()):
        $query->the_post();
        $post_id = $post->ID;
        ?>
        <li class="thumb <?php echo $post_id; ?>" onclick="changeContent(<?php echo $post_id; ?>);">
        <?php if(has_post_thumbnail())
        the_post_thumbnail('gallery-thumb');
        ?>
    
        <?php
        endwhile;
        wp_reset_query();
        }
        else{
        _e('No image found in gallery');
        }