How to save them when any of them are checked
You can use update_post_meta()
, like so:
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' );
}
}
I have also altered your 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
You can use get_post_meta()
to retrieve the ‘offers’ (i.e. array
of post IDs) — just like in the above op_render_menu_meta_box()
function
, and do a standard The Loop to display the post details. Example:
$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();