How to save them when any of them are checked
您可以使用
update_post_meta()
, 像这样:
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\' );
}
}
我还改变了你的
op_render_menu_meta_box()
:
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
}
}
and then use or echo those checked offers
您可以使用
get_post_meta()
检索“报价”(即。
array
发布ID的数量)&mdash;就像上面一样
op_render_menu_meta_box()
function
, 并执行标准的循环以显示帖子详细信息。示例:
$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();