Home > Blockchain >  Getting the post all categories with comma separated
Getting the post all categories with comma separated

Time:04-02

I am trying to get the categories in a post like this example if the post is added in cate1, cate2, and cate3 then the post-show 3 categories like cate1, cate2, cate3 if the post is posted in one category then just show the cate1 without a comma. But my code $slug = $category->slug; only shows one category in the post. here is my full code.

<?php
            $mi_args = array(
            'post_status'    => 'publish',
            'posts_per_page' => '99999',
            'post_type'      => 'blog'
            );
            $mi_query = new WP_Query($mi_args);
            if($mi_query->have_posts()):
            while ($mi_query->have_posts()): $mi_query->the_post();
            $portfolio_url = get_post_meta( get_the_ID(), 'portfolio_url_portfolio-url', true );
            $hover_color = get_post_meta( get_the_ID(), 'hove_color_hover-color', true );
            // Getting the category slug
            $work_category = get_the_terms( get_the_ID(), 'blog_categories' );
            foreach ($work_category as $category)
            { 
                $slug = $category->slug;
            ?>
            <div  data-category="<?php echo $slug; ?>">
            <?php
            }
            ?>
            <?php endwhile; endif; wp_reset_postdata(); ?>

CodePudding user response:

If I understand your question, you want to take an array of category slugs, and put them as a comma separated list?

If that's right, then you want to push your slugs to an array, and then implode it to a list.

<?php
$mi_args  = array(
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'post_type'      => 'blog',
);
$mi_query = new WP_Query( $mi_args );
if ( $mi_query->have_posts() ) :
    while ( $mi_query->have_posts() ) :
        $mi_query->the_post();
        $portfolio_url = get_post_meta( get_the_ID(), 'portfolio_url_portfolio-url', true );
        $hover_color   = get_post_meta( get_the_ID(), 'hove_color_hover-color', true );
        // Getting the category slug.
        $work_category = get_the_terms( get_the_ID(), 'blog_categories' );
        $slug          = array();
        foreach ( $work_category as $category ) {
            $slug[] = $category->slug;
        }
        $slug_list = implode( ',', $slug );

        ?>

    <div  data-category="<?php echoesc_attr( $slug_list ); ?>">

    <?php
    endwhile;
    endif;
    wp_reset_postdata();
?>
  • Related