我正在使用CMB2和CMB2帖子搜索字段在不同类型的帖子(包括自定义帖子类型)之间创建一对多链接,帖子搜索字段位于可重复的元框组中,以便每个连接的帖子都有一些文本来提供连接的上下文。我已经让它正常工作了-除非一个帖子没有任何连接的帖子。如果字段/组为空,我的帖子/页面模板将重复主要帖子内容,而不是预期的连接帖子。
设置我的metabox:
function gwl_register_post_connection_metabox() {
$prefix = \'gwl_collection_post_connection_\';
$cmb_group = new_cmb2_box( array(
\'id\' => $prefix . \'metabox\',
\'title\' => __( \'Connected posts\', \'gwl-cd\' ),
\'object_types\' => array( \'post\',\'page\',\'gwl_exhibition\' ),
) );
$group_field_id = $cmb_group->add_field( array(
\'id\' => $prefix . \'group\',
\'type\' => \'group\',
\'description\' => __( \'You can connect different collection items and names, as well as posts and other content from across the website.\', \'gwl-cd\' ),
\'options\' => array(
\'group_title\' => __( \'Connected post {#}\', \'gwl-cd\' ),
\'add_button\' => __( \'Add another post\', \'gwl-cd\' ),
\'remove_button\' => __( \'Remove post\', \'gwl-cd\' ),
\'sortable\' => true,
),
) );
$cmb_group->add_group_field( $group_field_id, array(
\'name\' => __( \'Connected Post\', \'gwl-cd\' ),
\'description\' => __( \'Select an item, name or post by entering the post ID, or click on the search symbol to find a post\', \'gwl-cd\' ),
\'id\' => $prefix . \'related_post\',
\'type\' => \'post_search_text\',
\'post_type\' => array( \'post\',\'page\',\'gwl_exhibition\',\'gwl_name\',\'gwl_item\' ),
\'select_type\' => \'radio\',
\'select_behavior\' => \'replace\',
) );
$cmb_group->add_group_field( $group_field_id, array(
\'name\' => __( \'Context\', \'gwl-cd\' ),
\'description\' => __( \'How does this collection item or other post relate to the main article?\', \'gwl-cd\' ),
\'id\' => $prefix . \'context\',
\'type\' => \'wysiwyg\',
\'options\' => array(
\'media_buttons\' => false, // hide insert/upload button(s) << TBD
\'textarea_rows\' => get_option(\'default_post_edit_rows\', 6),
),
) );
}
显示连接的帖子:
function gwl_output_connections( $gwl_collection_post_connection_group ) {
$connections = get_post_meta( get_the_ID(), \'gwl_collection_post_connection_group\', true );
if ( ! empty( $connections ) ) {
foreach ( (array) $connections as $key => $connection ) {
$relpost = $desc = \'\';
if ( isset( $connection[\'gwl_collection_post_connection_related_post\'] ) )
$relpost = esc_html( $connection[\'gwl_collection_post_connection_related_post\'] );
if ( isset( $connection[\'gwl_collection_post_connection_context\'] ) )
$desc = wpautop( $connection[\'gwl_collection_post_connection_context\'] );
echo \'<div class="connected-post"><h3><a href="\';
echo get_permalink( $relpost );
echo \'">\';
echo get_the_title( $relpost );
echo \'</a></h3> <p>\';
echo get_the_excerpt( $relpost );
echo \'</p><p>\';
echo $desc;
echo \'</p></div>\';
}
}
else {
echo \'<p>There are no connected posts.</p>\';
}
}
(我尝试了!empty check和isset的变体,但在没有连接的post时,无法正确显示最后一行)