0

I've created a plugin with a meta box that has a check box and noticed that when a post goes from scheduled (future) to published the meta is no longer checked.

When I schedule the post and check the box, it stays saved. If the post is published and I check the box it stays checked. Going from published to draft keeps the box checked.

I don't know what I'm doing wrong. Here is my code:

add_action('add_meta_boxes', 'add_feature_meta');

function add_feature_meta() {
    if(current_user_can('edit_posts')) {
        add_meta_box('feature_meta_id', 'Feature this Article?', 'feature_meta_box', 'post', 'side', 'high');
    }
}

function feature_meta_box() {
    global $post;
    $feature_data = get_post_meta($post->ID, 'feature_meta_id', true);
    ?>

        <label for="featured-meta"><input type="checkbox" id="featured-meta" name="feature_meta_id" <?php if($feature_data == '1') { echo 'checked'; } ?>> Make this featured</label>

    <?php
}

function k2_feature_meta_save_details($post_id) {
    global $post;

    if((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || (defined('DOING_AJAX') && DOING_AJAX)) {
        return;
    }

    if(isset($_POST['feature_meta_id'])) {
        $feature_data = 1;
    } else {
        $feature_data = 0;
    }

    update_post_meta($post_id, 'feature_meta_id', $feature_data);

}

add_action('save_post', 'k2_feature_meta_save_details');

1 Answer 1

3

I have not tested this, but my guess is that $_POST is not set when the post is saved when wp_cron changes the status from "Scheduled" to "Published", and so your value gets saved/reset to 0.

Instead of using save_post you could hook to the several transition hooks that fit your needs.

Or you could remove your action for the one or more transitions that seem to be problematic. For example:

add_action(
  'pending_to_publish',
  function($post) {
    remove_action('save_post', 'k2_feature_meta_save_details');
  }
);

Untested, but I hope that helps.

1
  • 1
    Thanks for this, I don't know why that didn't click for me. FYI, I changed pending_to_published to future_to_published
    – kel
    Jan 23, 2014 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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