CMB2 Attached Posts 插件使用教程
项目介绍
CMB2 Attached Posts 是一个用于 WordPress 的开源插件,它扩展了 CMB2(Custom Meta Boxes 2)的功能,允许用户将文章附加到页面。这个插件通过提供一个自定义字段,使得用户可以轻松地将多个文章关联到一个页面,并且支持通过拖放来重新排列这些文章的顺序。
项目快速启动
安装
- 下载插件:从 GitHub 仓库 CMB2/cmb2-attached-posts 下载插件。
- 上传插件:将下载的插件文件上传到你的 WordPress 站点的
wp-content/plugins
目录。 - 激活插件:在 WordPress 管理后台的“插件”页面中激活 CMB2 Attached Posts 插件。
配置
以下是一个简单的示例代码,展示如何在你的主题中使用 CMB2 Attached Posts 插件:
// 在 functions.php 文件中添加以下代码
add_action( 'cmb2_admin_init', 'cmb2_attached_posts_field' );
function cmb2_attached_posts_field() {
$cmb = new_cmb2_box( array(
'id' => 'test_metabox',
'title' => __( 'Attached Posts', 'cmb2' ),
'object_types' => array( 'page' ), // 适用于页面
) );
$cmb->add_field( array(
'name' => __( 'Attached Posts', 'cmb2' ),
'desc' => __( 'Drag posts from the left column to the right column to attach them to this page.', 'cmb2' ),
'id' => 'attached_posts_field',
'type' => 'custom_attached_posts',
'options' => array(
'show_thumbnails' => true, // 显示缩略图
'query_args' => array(
'posts_per_page' => 10,
'post_type' => 'post',
),
),
) );
}
显示附加的文章
在你的页面模板文件中,使用以下代码来显示附加的文章:
<?php
$attached_posts = get_post_meta( get_the_ID(), 'attached_posts_field', true );
if ( $attached_posts ) {
foreach ( $attached_posts as $post_id ) {
$post = get_post( $post_id );
?>
<div class="attached-post">
<h2><?php echo get_the_title( $post ); ?></h2>
<?php echo get_the_post_thumbnail( $post, 'thumbnail' ); ?>
<p><?php echo wp_trim_words( get_the_excerpt( $post ), 30 ); ?></p>
</div>
<?php
}
}
?>
应用案例和最佳实践
应用案例
- 项目组合页面:在一个项目组合页面中,展示与该项目相关的多个文章或案例研究。
- 产品页面:在产品页面中,展示与该产品相关的用户评价或相关文章。
- 活动页面:在活动页面中,展示与该活动相关的多个新闻报道或博客文章。
最佳实践
- 优化查询:在使用
get_post_meta
和get_post
函数时,确保查询的性能优化,避免在循环中多次查询数据库。 - 响应式设计:确保附加的文章在不同设备上都能良好显示,特别是拖放功能在移动设备上的体验。
- 安全性:在显示附加文章的内容时,确保进行适当的过滤和转义,防止 XSS 攻击。
典型生态项目
CMB2 Attached Posts 插件是 CMB2 生态系统的一部分,CMB2 是一个强大的自定义字段插件,广泛用于 WordPress 开发。以下是一些与 CMB2 相关的典型生态项目:
- CMB2 Field Type:扩展 CMB2 的字段类型,提供更多自定义选项。
- CMB2 Conditionals:允许在