0
点赞
收藏
分享

微信扫一扫

wordpress调用指定ID分类内容 并判断第一个给添加特殊属性

在WordPress中,如果你想要在首页调用指定ID分类下的6个内容,并且对第一个内容进行特殊处理,你可以使用自定义的WordPress查询来实现。以下是一个示例代码,展示了如何实现这一功能:

<?php // 指定分类ID $category_id = 666; // Replace with your category ID

// Query 6 contents under the specified category $args = array( 'category' => $category_id, 'posts_per_page' => 6, 'orderby' => 'date', 'order' => 'DESC' );

$custom_query = new WP_Query($args);

if ($custom_query->have_posts()) : $first_post = true; // wodepress.com Is marking the first content while ($custom_query->have_posts()) : $custom_query->the_post(); if ($first_post) { // Special handling of the first content echo '<div class="first-post">'; the_title('<h2>', '</h2>'); the_content(); echo '</div>'; $first_post = false; // Reset Tag } else { // Handling of other content echo '<div class="other-post">'; the_title('<h3>', '</h3>'); the_excerpt(); echo '</div>'; } endwhile; wp_reset_postdata(); // Reset article data else : echo 'No content found'; endif; ?> 解释

指定分类ID:将 $category_id 设置为你想要调用的分类ID。

查询参数:使用 WP_Query 进行自定义查询,指定分类ID、每页显示的文章数量、排序方式等。

循环处理内容:在循环中,使用 $first_post 变量来标记是否是第一个内容,并根据标记进行不同的处理。

特殊处理第一个内容:如果是第一个内容,可以添加特殊的HTML结构或样式。

重置文章数据:使用 wp_reset_postdata() 函数来重置文章数据,以便后续的WordPress函数能够正常工作。

注意事项

确保在主题的 functions.php 文件中添加此代码,或者在一个自定义插件中添加。

替换 $category_id 为你实际想要调用的分类ID。

根据需要调整HTML结构和样式。

通过这种方式,你可以在WordPress首页调用指定分类下的内容,并对第一个内容进行特殊处理。

原文 https://www.jianzhanpress.com/?p=8186

举报

相关推荐

0 条评论