该功能是通过这种方式实现的!
function op_register_menu_meta_box() {
add_meta_box(
\'op-menu-meta-box-id\', // Metabox ID
esc_html__( \'Custom offers Checklist (select any 2)\', \'text-domain\' ), //Metabox Title
\'op_render_menu_meta_box\', // Metabox Callback Function
\'listing\' // Place Where this Metbax Should Appear
);
}
add_action( \'add_meta_boxes_listing\', \'op_register_menu_meta_box\' ); //Metabox Hook
The callback function!
function op_render_menu_meta_box( $post ) { // Metabox Callback Function Called
// Get the selected \'offers\' (array of post IDs).
$offers_ids = (array) get_post_meta( $post->ID, \'_offers_ids\', true );
// Displays a nonce field, without referrer field.
wp_nonce_field( \'save-offers-meta\', \'offers_meta_nonce\', false );
// Metabox content
$getPostsToSelect = get_posts(
array(
\'post_type\' => \'offers\',
\'posts_per_page\' => 3,
));
foreach ($getPostsToSelect as $aPostsToSelect) {
?>
<label>
<input
type=\'checkbox\'
name=\'offers_meta[]\'
class=\'postsToSelect\'
value=\'<?php echo $aPostsToSelect->ID ?>\'
<?php checked( true, in_array( $aPostsToSelect->ID, $offers_ids ) ); ?>
/>
<?php echo $aPostsToSelect->post_title;
?>
</label><br/>
<?php
}}
Save Metabox function!
add_action( \'save_post\', \'op_save_offers_meta\', 10, 2 );
function op_save_offers_meta( $post_id, $post ) {
// Make sure that we can save the meta data.
if ( ( empty( $post_id ) || empty( $post ) || ( \'listing\' !== get_post_type( $post ) ) )
|| ( empty( $_POST[\'post_ID\'] ) || $_POST[\'post_ID\'] != $post_id || ! isset( $_POST[\'offers_meta\'] ) )
|| ( empty( $_POST[\'offers_meta_nonce\'] ) || ! wp_verify_nonce( $_POST[\'offers_meta_nonce\'], \'save-offers-meta\' ) )
|| ( ! current_user_can( \'edit_post\', $post_id ) ) ) {
return;
}
$offers_ids = wp_parse_id_list( $_POST[\'offers_meta\'] );
if ( ! empty( $offers_ids ) ) {
update_post_meta( $post_id, \'_offers_ids\', $offers_ids );
} else {
delete_post_meta( $post_id, \'_offers_ids\' );
}
}
At last the procedure to echo checked !
<?php $post_id = get_the_ID();
// Get the selected \'offers\' (array of post IDs).
$offers_ids = (array) get_post_meta( $post_id, \'_offers_ids\', true );
$q = new WP_Query( [
\'post_type\' => \'offers\',
\'post__in\' => $offers_ids,
] );
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
?>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
<?php
}
}
wp_reset_query ?>
Big thanks to @sallycj