仅在首页上显示WordPress帖子的第一句作为“突出显示的帖子”部分

时间:2017-07-17 12:24:04

标签: php wordpress

我正在制作我的第一个WordPress主题,我想在index.php上创建一个“突出显示的帖子”部分。这里有很多脚本,但似乎都在整个index.php上应用了永久过滤器。这是有问题的,因为我想在下面的index.php上显示整个帖子。有没有办法只为这部分应用这个特殊的过滤器而不是整个index.php?

1 个答案:

答案 0 :(得分:1)

如果您可以向我们提供更多信息,以确定这些“突出显示”的帖子,我们可以更具体地解决此问题。

但同时我猜它是两个最新的帖子,这意味着你可以在index.php中有两个查询

首先是“突出”的那些:

<?php
  $args = array( 'numberposts' => 2 );
  $lastposts = get_posts( $args );
  foreach($lastposts as $post) : setup_postdata($post); 
?> 

  <h2 class="news"><?php the_title(); ?></h2>
  <?php the_excerpt(); ?>

<?php endforeach; ?>

这将为您提供此查询中的帖子的摘录。

你可以做的是限制摘录到你想要的任何长度,并添加阅读更多链接,如果你想:)

function newExcerpt($more) {
   global $post;
   return '... <a href="'. get_permalink($post->ID) . '">Read more</a>';
}
add_filter('excerpt_more', 'newExcerptReadMore');


function customExcerptLength( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'customExcerptLength', 999 );

对于其他帖子,您可以执行其他查询但不使用前两个帖子,如下所示:

$count = 0;
$lastposts = get_posts();
foreach($lastposts as $post) : setup_postdata($post); 
if($count > 1)
?> 

  <h2 class="news"><?php the_title(); ?></h2>
  <?php the_excerpt(); ?>
  $counter++;

<?php endforeach; ?>

这将循环播放帖子并跳过前两个帖子。 如果您有其他一些术语或类别或其他确定突出显示帖子的内容,那么您可以使用它并将其作为参数传递给get_posts($ args)。