Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get child of Category(Parent Child relation)

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 438
    Comment on it

    Hello reader's today we discussed about "How to get child of Category".

    In Wordpress, if we create a category and their sub category and we want to call category and their sub-category. In Programming language we called it Parent Child relation. The below code define how parent child relation work. We can create a custom post type called gallery and taxonomy name is gallery-category. $images store all the featured image of the category. "$term_id = $term->term_id" with this we can find the current category id.

        <?php
    
        $term =  get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
    
        $term_id = $term->term_id;
        function category_has_children() {
            global $wpdb;   
            $term = get_queried_object();
            $category_children_check = $wpdb->get_results(" SELECT * FROM wp_term_taxonomy WHERE parent = '$term->term_id' ");
            if ($category_children_check) {
                return true;
            } else {
               return false;
            }
        }
    
       if(!category_has_children()){
        $my = get_posts(array(
            'post_type' => 'gallery',
            'posts_per_page'  => -1,
            'order'     => 'ASC', 
            'tax_query' => array(
                array(
                'taxonomy' => 'gallery-category',
                'field' => 'term_id',
                'terms' => $term_id)
            ))
        );
        foreach ($my as $post) {
            $full_img = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
            $images = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'post-thumb');
    ?>
        <div class="col-sm-4 gallerypic">
            <a class="fancybox" href="<?php echo $full_img[0];?>" data-fancybox-group="gallery" title="<?php the_title(); ?>">
                <img src="<?php echo $images[0];?>" alt="" />
                <h4><?php echo $post->post_title; ?></h4>
            </a>
        </div>
    
    <?php
            }
        }
    ?>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: