将每个 wordpress post "Category" 放入它自己独特的 Div Class

Putting each wordpress post "Category" in it's own unique Div Class

我正在使用 PHP 和 ACF 使用“WordPress 帖子”创建一个投资组合页面(这对我来说很好地吐出 single.php 页)。我试图找到一种方法将每个“类别”放在自己的 div 中。这将允许我在每个 filter 中设置内容布局的样式。请看下面的例子。也许我应该换一种方式?

• 过滤器 1 - 1 列布局
• 过滤器 2 - 3 列布局

example of filter 1 example of filter 2

TLDR:尝试将每个 WordPress 类别的内容放入其自己的 div。

    <div class="work">

        <?php if (has_post_thumbnail() ): ?>
            <a href="<?php the_permalink(); ?>" class="blogimage">
                <?php the_post_thumbnail( 'medium' ); ?>
            </a>
        <?php endif; ?>
        
            <div class="work-copy">
                
                <div class="category">
                    <?php echo get_the_category_list(); // Display categories as links within ul ?>
                </div>
                
                <h2 class="headline">
                    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?><i class="fal fa-chevron-right"></i></a>             
                </h2>
                
            </div>   
    </div>
    
<?php endwhile; ?>

WordPress 自动将 CSS class 添加到整个网站的不同元素。这些包括正文 class 和 post class.

例如,如果您查看类别存档页面然后使用检查工具,您会注意到 body 标签中的类别和类别名称 CSS classes。

类别 class 由 WordPress 添加到 body 元素

您可以使用此 CSS class 通过添加自定义 CSS.

为每个类别设置不同的样式

你可以找到more details here

经过一些研究,这是一个非常简单的修复,这是我发现有用的答案;

<?php $category = get_the_category(); ?>
<div class="category-<?php echo $category[0]->slug ?>">

将其放在每个 post 中。为了在 div 中为每个 div class 设置相同的样式,您需要在 if / while 语句之间放置一个包含 div 的内容。然后,您将使用 div.

放置每个“类别过滤器”的内容
<?php if ( have_posts() ) : // Do we have any posts in the database that match our query? ?>
<div class="work-container">
    <?php while (have_posts()) : the_post(); ?> <!-- Finds the post -->
    
        <?php $category = get_the_category(); ?>
        <div class="category-<?php echo $category[0]->slug ?>"> <!-- This calls out the Category in the WP Post -->
                                            
            <div class="work-group">
                <?php if (has_post_thumbnail() ): ?>
                    <a href="<?php the_permalink(); ?>" class="blogimage">
                        <?php the_post_thumbnail( 'medium' ); ?>
                    </a>
                <?php endif; ?>
            </div> 
        </div>
    <?php endwhile; ?>
</div>
<?php endif; ?>

这里已经回答了这个问题,玩了一会儿我就开始工作了,希望这对别人有帮助! Get the name of the first category