0

I have a custom post type of people with some custom taxonomy boxes, i want to hide these when on child pages. I have found remove_meta_box works fine but i just can't access the $post object within the action.

Currently i have

function remove_post_custom_fields($post) {
  global $post;
  if( count($post->ancestors) > 0 ){
    remove_meta_box( 'staff-typediv' , 'people' , 'normal' );
    remove_meta_box( 'practice-areadiv' , 'people' , 'normal' ); 
  }
}
add_action( 'admin_menu' , 'remove_post_custom_fields' );

I have tried count($post->ancestors) > 0 and also just $post->post_parent but neither work.

Anyone any clue how to access $post variables within this action?

1

You should create a small custom function to check the current post (page or other post type) if is parent exist, like the follow function.

/**
 * if the post is a subpage for ID.
 *
 * $post object The post.
 * 
 * return boolean
 */
function is_child( $post ) {

    // If is sub_post
    if ( is_page() && ( $post->post_parent === $post->ID ) ) 
               return TRUE;
    else 
               return FALSE;
};

I think it is sufficient to check the type and the post_parent param, but with the ID is it clean and solid. For your requirements should you switch the is_page() conditional function to ( 'people' === get_post_type() ).

The helper function is_child can you now use in your test before you remove the meta boxes, like this.

add_action( 'admin_menu' , 'remove_post_custom_fields' );
function remove_post_custom_fields( $post ) {

  if ( is_child( $post ) ){
    remove_meta_box( 'staff-typediv' , 'people' , 'normal' );
    remove_meta_box( 'practice-areadiv' , 'people' , 'normal' ); 
  }
}
  • 1
    It would be nice to get rid of the global stuff ;-) – birgire Sep 5 '16 at 15:59
  • You have right, was not in my focus on this question, but it is a point for clean coding. – bueltge Sep 5 '16 at 16:09
1

You can try the do_meta_boxes hook:

add_action( 'do_meta_boxes', function( $post_type, $context, $post )
{
    // Nothing to do if context isn't 'normal'
    if( 'normal' !== $context )
        return;

    // Nothing to do if post type isn't 'people'
    if( 'people' !== $post_type )
        return;

    // Nothing to do with no post parents
    if( $post instanceof \WP_Post && 0 == $post->post_parent )
        return;

    // Remove meta boxes
    foreach( [ 'staff-typediv', 'practice-areadiv' ] as $id )   
        remove_meta_box( $id, $post_type, $context );

}, 10, 3 );

Here we target the normal context, but hopefully you can adjust it to your needs.

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.