您需要将自定义字段(单选按钮)添加到帖子编辑器中。要添加自定义字段和元框,我通常使用元框。io插件,您可以下载它并在其官方页面上获取该插件的文档:https://metabox.io/
使用metabox放置单选按钮。io您必须在函数中添加类似的内容。安装并激活插件后的php文件:
<?php //Don\'t use me if on functions.php
add_filter( \'rwmb_meta_boxes\', \'your_prefix_radio_demo\' );
function your_prefix_radio_demo( $meta_boxes )
{
$meta_boxes[] = array(
\'title\' => __( \'Content or Excerpt\', \'your-prefix\' ),
\'fields\' => array(
array(
\'name\' => __( \'Show Content\', \'your-prefix\' ),
\'id\' => \'content_or_excerpt\',
\'type\' => \'radio\',
\'options\' => array(
\'content\' => __( \'Show Complete Content\', \'your-prefix\' ),
),
),
)
);
return $meta_boxes;
}
然后,您可以查询所有帖子并检索单选按钮的值,以显示完整的内容或摘录(此代码适用于任何有主页代码的地方,例如index.php、自定义模板或模板部分):
$args = array(
\'post_type\' => \'post\',
\'posts_per_page\' => 12,
);
$query = new WP_Query( $args );
if($query->have_post()) {
while($query->have_posts()) {
$query->the_post();
$show_content = rwmb_meta( \'content_or_excerpt\' ); //Get the value of the post custom field
$thumbnail_url = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ) );
?>
<div class="home_featured_post">
<?php the_title(\'<h2>\', \'</h2>\'); ?>
<img src="<?php echo $thumbnail_url; ?>">
<?php
if( $show_content == "content" ) {
the_content();
} else {
the_excerpt();
}
?>
</div>
<?php
}
}
wp_reset_query();
为了让阅读更多链接链接到帖子,我从Codex中获取了以下代码:
https://developer.wordpress.org/reference/functions/the_excerpt/ (此代码位于functions.php文件中)
/**
* Filter the "read more" excerpt string link to the post.
*
* @param string $more "Read more" excerpt string.
* @return string (Maybe) modified "read more" excerpt string.
*/
function wpdocs_excerpt_more( $more ) {
return sprintf( \'<a class="read-more" href="%1$s">%2$s</a>\',
get_permalink( get_the_ID() ),
__( \'Read More\', \'textdomain\' )
);
}
add_filter( \'excerpt_more\', \'wpdocs_excerpt_more\' );