如何在WordPress中显示“精选内容”

您的博客中可能有想要向读者强调的故事。 通常将其称为“精选帖子”或“精选内容”。 如果您使用的是WordPress,则可以通过多种方式来显示这些特色文章,其中一种方式是使用Jetpack之类的插件。

Jetpack包含我们在WordPress.com中找到的功能。 在撰写本文时,它拥有30个功能,包括WordPress.com统计信息,光子, 无限滚动以及我们今天关注的重点内容 。 让我们开始吧。

添加主题支持

你需要做的第一件事情就是添加add_theme_support功能在你的主题的functions.php。

add_theme_support( 'featured-content', array(
	'featured_content_filter' => 'mytheme_get_featured_content',
));

添加后,您将在“ 设置”>“阅读”页面下找到一个新表单,“特色内容

添加主题支持

指定特色内容的标签名称,设置要显示的帖子数量,然后选中复选框以防止该标签出现在您的博客中。 分配您要标记为“ 特色”的帖子。

显示内容

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

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

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

function twentytwelve_get_featured_content() {
	apply_filters( 'twentytwelve_featured_content', array() );
}

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

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' )下方的某处添加以下代码。

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

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

<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中 ,我们使用get_template_part()调用该模板,并将其放入循环中,如下所示:

<?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之后,我们将获得一小段精选的特色内容。

最后结果

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


翻译自: https://www.hongkiat.com/blog/wordpress-featured-content/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值