How can i add a metabox to pull list of custom posts (any two) on edit or add post screen?

You can add a metabox in the edit screen with

add_action( 'add_meta_boxes', function () {
    add_meta_box(
        'yourcustom_sectionid', 
        __( '👋 Custom Meta Box', 'yourtextdomain' ), 
        function ( $post ) {
            wp_nonce_field( plugin_basename( __FILE__ ), 'yourcustom_noncename' );
            $cstm = get_post_meta(get_the_ID(),'yourcustom_meta',true);
            echo "<pre>".print_r($cstm,true)."</pre>";
        }, 
        'page'
    );
} );

You can query posts with get_posts() and add some check boxes inside that metabox

$getPostsToSelect = get_posts('post_type=post&numberposts=-1');
foreach ($getPostsToSelect as $aPostsToSelect) {
    ?>
    <label>
        <input 
          type="checkbox" 
          name="yourcustom_meta[]" 
          class="postsToSelect"
          value="<?php echo $aPostsToSelect->ID ?>"
         /> 
        <?php echo $aPostsToSelect->post_title ?>
    </label><br />
    <?php
}

You’d than need some jQuery to restrict to only 2 selected. It’d be somthing like

var limit = 2;
jQuery('input.single-checkbox').on('change', function(evt) {
   if(jQuery('input.single-checkbox:checked').length > limit) {
       this.checked = false;
   }
});

You’d save it all with somthing like :

add_action( 'save_post', function ( $post_id ) {

     if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
          return;
     if ( !wp_verify_nonce( $_POST['yourcustom_noncename'], plugin_basename( __FILE__ ) ) )
          return;
     if ( 'page' == $_POST['post_type'] ) { // not the Post Type
          if ( !current_user_can( 'edit_page', $post_id ) )
               return;
     } else {
          if ( !current_user_can( 'edit_post', $post_id ) )
               return;
     }

     update_post_meta($post_id,'yourcustom_meta',$_POST['yourcustom_meta']);
});

Then in your single.php, or wherever your loop is that you want them to show, you’d just call them up:

$cstm = get_post_meta(get_the_ID(),'yourcustom_meta',true);
foreach ($cstm as $aPostToDisplay) {
    echo "<pre>{$aPostToDisplay->ID} - {$aPostToDisplay->post_title}</pre>";
}

Please note that I free handed this (not tested), so copy/paste will not work.. It’s more of a logic guid.

I’ve assumed without double checking that name="yourcustom_meta[]" will pass only the checked ones to $_POST['yourcustom_meta'], but you might want to confirm that.

I’ve also used anonymous functions, which probably shouldn’t be used if this is a for-public plugin/theme.

Leave a Comment