Global Variable vs Local Variable

// MOVE REVISIONS METABOX TO BOTTOM OF EDIT-FORM.PHP
$post_types = get_post_types();
add_action('do_meta_boxes', 'batteryboys_reorder_meta_boxes');
function batteryboys_reorder_meta_boxes(){
    remove_meta_box( 'revisionsdiv', $post_types, 'normal' );
    add_meta_box('revisionsdiv', __('Revisions'), 'post_revisions_meta_box', $post_types, 'normal', 'low');
}

This code works fine, however when you move the $post_types = get_post_types(); inside of the function, it does not work.

Is this because the get_post_types() function has to be global to execute and by containing it inside the function I am restricting it to just inside the function? In other words, it can’t get out to query the database, right?

2 Answers
2

As @Milo pointed out, when you use code in OP $post_types is undefined inside the function, so WordPress will act just like it was not there at all.

However, that means you are using an undefined variable, and if turn WP_DEBUG on you’ll see a warning, and so you can notice you are doing something wrong.

That’s one of the reasons you always should develop with debug turned on.

Regarding your problem, sure run a foreach can be a solution, but is not needed in your case, reason is that 'do_meta_boxes' hook pass screen id (that is post type name) as argument, so you can use it to remove and add your metabox.

add_action('do_meta_boxes', 'batteryboys_reorder_meta_boxes', 1);

function batteryboys_reorder_meta_boxes($screen){
    if ($screen === 'dashboard') return;
    remove_meta_box( 'revisionsdiv', $screen, 'normal' );
    add_meta_box(
      'revisionsdiv', __('Revisions'), 'post_revisions_meta_box', $screen, 'normal', 'low'
    );
}

Leave a Comment