WordPress主题分类列表中显示当前分类下的置顶文章,并在下面显示最新发布的文章

941次阅读
没有评论

在这个代码中,我们首先获取当前分类的ID ($cat_id) 和所有置顶文章的ID数组 ($sticky_posts)。

然后,我们使用 WP_Query 分别查询当前分类下的置顶文章和最新发布的文章。对于置顶文章,我们设置查询参数,包括 post__in 用于指定置顶文章ID数组,category__in 用于限制只查询当前分类,以及 ignore_sticky_posts 设置为 1,忽略其他位置的置顶文章。

对于最新发布的文章,我们使用分类ID ($cat_id) 并排除置顶文章的ID数组 ($sticky_posts),以确保只显示最新发布的非置顶文章。

最后,我们使用默认的 have_posts()the_post() 循环来显示置顶文章和最新发布的文章。

请确保将上述代码嵌入到适当的WordPress主题文件中,并根据需要自定义HTML和样式。

<?php
$cat_id = get_queried_object_id();
$sticky_posts = get_option('sticky_posts');

// 查询当前分类下的置顶文章
$sticky_args = array(
  'post__in' => $sticky_posts,
  'category__in' => array($cat_id),
  'ignore_sticky_posts' => 1
);
$sticky_query = new WP_Query($sticky_args);

// 查询当前分类下的最新发布文章
$new_posts_args = array(
  'cat' => $cat_id,
  'post__not_in' => $sticky_posts
);
$new_posts_query = new WP_Query($new_posts_args);

// 显示置顶文章
if ($sticky_query->have_posts()) :
  while ($sticky_query->have_posts()) : $sticky_query->the_post();
    ?>
    <li>
      <div class="pbox"><a href="<?php the_permalink(); ?>"><img src="<?php echo get_template_directory_uri(); ?>/timthumb.php?src=<?php echo post_thumbnail_src(); ?>&h=500&w=500&zc=1" border="0" alt="<?php the_title(); ?>"></a></div>
      <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
    </li>
    <?php
  endwhile;
  wp_reset_postdata();
endif;

// 显示最新发布的文章
if ($new_posts_query->have_posts()) :
  while ($new_posts_query->have_posts()) : $new_posts_query->the_post();
    ?>
    <li>
      <div class="pbox"><a href="<?php the_permalink(); ?>"><img src="<?php echo get_template_directory_uri(); ?>/timthumb.php?src=<?php echo post_thumbnail_src(); ?>&h=500&w=500&zc=1" border="0" alt="<?php the_title(); ?>"></a></div>
      <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
    </li>
    <?php
  endwhile;
  wp_reset_postdata();
endif;
?>

正文完
 0
评论(没有评论)

觅站网

Posts

Sed cras ornare arcu dui vivamus arcu felis. Cursus euismod quis viverra nibh cras pulvinar mattis nunc.

Melissa Meiers