2

I want to add metabox to pull list of custom posts and select any two of them on edit or add post screen. And At last when the post is published display them on single post page. Please help me! Any help will be appreciated....

    add_action( 'add_meta_boxes', function () {
    add_meta_box(
        'yourcustom_sectionid', 
        __( '👋 Custom Offer Section', '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>";
            $getPostsToSelect = get_posts('post_type=offers&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
}
        }, 
        'listing'
    );
} );

and then below:

echo "<script type='text/javascript'>
  var limit = 2;
jQuery('input.single-checkbox').on('change', function(evt) {
   if(jQuery('input.single-checkbox:checked').length > limit) {
       this.checked = false;
   }
});
</script>";

but the jquery does not seems to work to select the two checked boxes... and after that problem please help me printing the the two selected checked posts.

the result i obtained till now is with 4 custom posts named offer in the image shown below enter image description here

  • What solutions have you tried already? – Krzysiek Dróżdż Mar 20 '18 at 18:11
  • i just added metabox somehow on edit screen! basic metabox with a text area. Please help me with specific code. – Nimesh Mar 21 '18 at 2:05
3

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.

  • Thanks for the instruction, i am new to php.... it would be great if you can help me with code i have cust post type ready, it is (listing). how would i get a metabox there, and inside that metabox we can select two posts published. Next mechanism after the selection we can print them on single custom post (listing) page. Thank You! Please help me with some specific code and guide me if possible. i have not much experience on it. – Nimesh Mar 21 '18 at 1:58
  • i added a metabox, but it appears blank as you can see in screenshot ibb.co/esdwAH – Nimesh Mar 21 '18 at 2:12
  • i updated the question just now..Please help me @david-sword – Nimesh Mar 21 '18 at 15:22
1

I know this question has been asked for a while but below is my own contribution;

add_action( 'add_meta_boxes', function () {
    add_meta_box(
        'yourcustom_sectionid', 
        __( '👋 Custom Meta Box', 'yourtextdomain' ), 
        'enter_your_callback_function_here', 
        'posttype_id',
        'side',
        'default'
     );
 } );

function enter_your_callback_function_here( $post ) {
    wp_nonce_field( 'saving_postlist_data', 'postlist_metabox_wpnonce' );

    $value = get_post_meta( $post->ID, '_add_your_meta_key', true );

    echo "<pre>".print_r($value,true)."</pre>";//This is for testing purpose, remove when you're done, this is just to see that your selection is added to the array

    $getAllPostsToSelect = get_posts('post_type=PostTypeToGetListFrom&numberposts=-1');

        ?>
        <div class="List_wrapper">
        <?php foreach ($getAllPostsToSelect as $dPostsToSelect): ?>
            <label>
                <input 
                  type='checkbox' 
                  name='_add_your_meta_key[]' 
                  class='postsToSelect'
                  value='<?php echo $dPostsToSelect->ID ?>'
                  <?php if ($value && in_array($dPostsToSelect->ID, $value) ? { echo ' checked="checked"'; } ?>
                 /> 
                <?php echo $dPostsToSelect->post_title ?>
            </label><br />
        <?php endforeach ?>
    </div>
    <?php
}

// //Save The custom Meta Data
function why_not_save_the_postlist_data( $post_id ) {
    //If nonce is not set by wordpress
    if ( ! isset( $_POST['postlist_metabox_wpnonce'] ) ) {
        return;
    }

    //If nonce is not verified by wordpress
    if ( ! wp_verify_nonce( $_POST['postlist_metabox_wpnonce'], 'saving_postlist_data' ) ) {
        return;
    }

    //If wordpress is doing auto-save, dont save metabox
    if ( define('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
        return;
    }

    //If user cant edit post
    if ( ! current_user_can( 'edit_post', $post_id )) {
        return;
    }

    $data = $_POST['_add_your_meta_key'];

    //Update the Data
    update_post_meta( $post_id, '_add_your_meta_key', $data );
}
add_action( 'save_post', 'why_not_save_the_postlist_data' );

Tested and worked. and you would get something like this;

enter image description here

You can style it as you want, below is the CSS i used to style that above screenshot;

#yourcustom_sectionid .inside {
    padding-bottom: 40px;
}
#yourcustom_sectionid .inside .List_wrapper {
    height: 150px;
    overflow-y: auto;
    border: 1px solid #dddddd;
    background: #fdfdfd;
    padding: 10px;
}



FRONT-END DISPLAY
The array stores the post IDs of the custom post type, so to get the post name and link in front-end, you need to do something like this;

global $post;

$arrayOfIDs = get_post_meta( $post->ID, '_add_your_meta_key', true );

<ul class="anythingHere">
    <?php foreach ($arrayOfIDs as $getPost) : ?>
        <li><a href="<?php echo get_permalink($getPost); ?>"><?php echo get_the_title($getPost); ?></a></li>  
    <?php endforeach; ?>
</ul>

Then the Output will look like this, with some CSS styling;

enter image description here

  • How is this different from the accepted answer? Can you please add explanation? – Nilambar Jul 10 at 4:13
  • The accepted answer doesn't check the value selected ( but it saves selection ) and the person who asked the question said he's new to Php and would want the entire snippet in a go. – Kolawole Emmanuel Izzy Jul 10 at 4:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.