gpt4 book ai didi

php - Wordpress - 为前 4 个帖子设置自定义 CSS 类,并包装前 2 个帖子

转载 作者:太空宇宙 更新时间:2023-11-04 06:37:22 26 4
gpt4 key购买 nike

好的,我创建的主页有 4 个最新帖子,每个帖子都必须有不同的类才能使用 CSS 设置样式。

我正在使用此代码显示 4 个最新帖子:

<?php 
// the query
$the_query = new WP_Query( array(
'category_name' => 'artykuly',
'posts_per_page' => 4,
'order' => 'ASC',
));
?>

<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<!---posty home--->
<div class="home-posty" style="background: #ccc; margin: 20px;">
<a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title(); ?></a>
<div class="home-post-opis">
<?php the_excerpt(); ?>
</div>
<div class="home-post-tags">
<?php the_tags(); ?>
</div>
<div class="home-post-date">
<?php echo get_the_date(); ?>
</div>
</div>

问题是如何设置 lates 4 post different class like: "first-post", "second-one", "third-post", "last-one"。它不能是帖子 ID 或标题,因为每个新帖子都有不同的 ID,布局必须始终相同。如何强制向他们添加我自己的类?我在考虑 CSS nth-child,但恕我直言,自定义类会更好。

我还需要包装(使用 DIV)其中的前两个。可能吗?

最佳答案

请使用add_filter 更改类列表。和 add_action 用于包装

add_filter('prefix_home_posts_classes', 'prefix_home_posts_classes', 10, 2);

function prefix_home_posts_classes( $classes, $index ) {
$post_order = $index % 4;

switch ( $post_order ) {
case 0:
$classes[] = 'last-one';
break;
case 3:
$classes[] = 'third-post';
break;
case 2:
$classes[] = 'second-one';
break;
case 1:
$classes[] = 'first-post';
break;
}

return $classes;
}

add_action('prefix_home_before_post', 'prefix_home_before_post');
add_action('prefix_home_after_post', 'prefix_home_after_post');

function prefix_home_before_post( $index ) {
if ($index === 1) {
echo '<div class="wrapper">';
}
}

function prefix_home_after_post( $index ) {
if ($index === 2) {
echo '</div>';
}
}

还有你的HTML模板,请换成这个

$index = 0; ?>
<?php if ($the_query->have_posts()) { ?>
<?php while ($the_query->have_posts()) { ?>
<?php $the_query->the_post(); ?>

<?php $index++; ?>
<?php $post_classes = apply_filters('prefix_home_posts_classes', ['home-posty'], $index); ?>
<?php $post_classes_string = implode(' ', $post_classes); ?>

<?php do_action( 'prefix_home_before_post', $index ); ?>
<div class="<?php echo esc_attr($post_classes_string); ?>" style="background: #ccc; margin: 20px;">
<a href="<?php echo esc_url(get_permalink()); ?>"><?php the_title(); ?></a>
<div class="home-post-opis">
<?php the_excerpt(); ?>
</div>
<div class="home-post-tags">
<?php the_tags(); ?>
</div>
<div class="home-post-date">
<?php echo get_the_date(); ?>
</div>
</div>
<?php do_action( 'prefix_home_after_post', $index ); ?>
<?php } ?>
<?php } ?>

关于php - Wordpress - 为前 4 个帖子设置自定义 CSS 类,并包装前 2 个帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54102014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com