简体   繁体   中英

Dynamically Echo the Category Slug of Wordpress Posts

I need to echo the category slug for each post for the data-filter value. Can someone advise what I'm doing wrong?

<div id="container" class="isotope">
    <?php 
    $args = array(
        'post_type' => 'Photos',
    );
    $_posts = new WP_Query($args);
    ?>
    <?php 
    if ( $_posts->have_posts() ) : while ( $_posts->have_posts() ) : $_posts->the_post(); ?>

<!-- Here is the issue -->
    <div class="grid-item" data-filter="
        <?php 
        $categories = get_the_category(get_the_id());
        foreach ($categories as $category){ 
        echo $category->slug.' ';}?>"
    >

    <a onClick='showDialog()' data-target="#lightbox">
    <img src="<?php the_field('image'); ?>" alt="">
    </a>
    </div>
    <?php
    endwhile; endif;
    ?>
</div>

Please change code like this

<?php    
$categories = get_the_category(get_the_ID());
        foreach ($categories as $category){ 
            $slug = $category->slug;
?>
<div class="grid-item" data-filter="<?php echo $slug; ?>">
<?php
        }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM