跳至正文

如何在 WordPress 中显示“特色内容”

如何在 WordPress 中显示“特色内容”

您可能希望在博客中向读者突出显示一些故事。这通常称为“特色帖子”或“特色内容”。如果您使用的是 WordPress,则可以通过多种方式显示这些精选帖子,其中之一是使用 Jetpack 等插件。

Jetpack包含我们在 WordPress.com 中找到的功能。在撰写本文时,它拥有 30 项功能,包括 WordPress.com Stats、Photon、 Infinite Scroll和我们今天的重点, Featured Content让我们开始吧。

添加主题支持

更新:从 Jetpack 3.7 开始,您可以在 Apperance > Customize Menu 下找到特色内容。

您需要做的第一件事是在主题的add_theme_supportfunctions.php 中添加函数

1个
2个
3个
add_theme_support( 'featured-content', array(
  'featured_content_filter' => 'mytheme_get_featured_content',
));

添加后,您会在“设置”>“阅读”页面下找到一个新表格“精选内容”。

添加主题支持

指定特色内容的标签名称,设置要显示的帖子数,然后勾选复选框以防止标签出现在您的博客上。使用标签分配您想要标记为精选的帖子。

显示内容

我们将添加几行代码来显示主题中的特色内容。而且,作为本教程中的示例,我将使用TwentyTwelve

通常特色内容显示在首页上。如果您的主题遵循 WordPress 标准主题结构,则首页会呈现在index.phphome.phpfront-page.php中。

打开functions.php,并添加以下函数以获取精选帖子并将它们放入数组中。

1个
2个
3个
function twentytwelve_get_featured_content() {
  apply_filters( 'twentytwelve_featured_content', array() );
}

我们可以像这样进一步扩展该代码。

1个
2个
3个
4个
5个
6个
7
8个
9
function twentytwelve_get_featured_content( $num = 1 ) {
  global $featured;
  $featured = apply_filters( 'twentytwelve_featured_content', array() );
 
  if ( is_array( $featured ) || $num >= count( $featured ) )
    return true;
 
  return false;
}

如果至少有一个存在并且页面没有被分页(它不在第二页之后),上面的条件语句将显示特色内容。

此外,我们还可以为特色内容设置新的缩略图大小。在此示例中,我创建了一个新尺寸,即 250 x 160 像素。您可以将以下代码添加到add_theme_support( 'post-thumbnail' ).

1个
2个
add_theme_support( 'post-thumbnails' );
add_image_size( 'twentytwelve-featured-thumb', 250, 160, true );

接下来,让我们创建一个名为featured.php的新模板,并在下面添加此代码以将特色内容放入适当的 HTML 结构中。

1个
2个
3个
4个
5个
6个
7
8个
9
<div class="featured-post clearfix">
  <figure class="post-thumbnail">
    <?php if ( has_post_thumbnail() ) { the_post_thumbnail('twentytwelve-featured-thumb'); } ?>
  </figure>
  <div class="post-entry">
    <h3 class="post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
      <?php the_excerpt(); ?>
  </div>
</div>

index.php中,我们通过 using 调用该模板get_template_part()并将其放入循环中,如下所示:

1个
2个
3个
4个
5个
6个
7
8个
<?php if ( twentytwelve_get_featured_content(1) ) : ?>
  <div id="featured">
    <h2><?php _e( 'Featured Content', 'twentytwelve' ); ?></h2>
    <?php foreach ( $featured as $post ) : setup_postdata( $post ); ?>
      <?php get_template_part( 'featured', get_post_format() ); ?>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

在这个阶段,我们在技术上已经完成,在添加一些 CSS 之后,我们将有一小部分特色内容。

最后结果

我们希望本教程对您有用,如果您在学习本教程时遇到问题,请随时在评论中告诉我们。

标签: