John John - 7 months ago 7
PHP Question

WordPress Admin Area - Add class to body of page edit screen

I used wp-types toolset to create a custom post type and a post relationship to pages; there is now a Post Relationships section at the bottom of every page edit screen. The problem is, I would only like this section to show up on a couple of pages.

Is there something I can add to functions.php (or another alternative) to hide this section from all page edit screens expect for those particular ones.

The section div id that I want to hide is #wpcf-post-relationship and the data post id of the pages that I would like it to be visible are 143 and 23.

Answer

-- (update) --

As admin_init is triggered before any other hook when a user access the admin area, we finally use instead admin_head because action is just triggered inside the <head> of the admin page. thanks to John

The easy way is to use a simple CSS rule with the 'admin-init' hook, to do it, like this:

1) create a css file named hide_some_field.css and put it into your active child theme folder, with this code:

#wpcf-post-relationship {
    display:none;
}

2) add codes into your active child theme in functions.php file:

add_action('admin_init', 'ts_hiding_some_fields');
function ts_hiding_some_fields(){
    // your 2 pages in this array
    $arr = array(23, 143);
    if(get_post_type() == 'page' && !in_array(get_the_ID(), $arr))
    {
        wp_enqueue_style( 'hide_some_field', get_stylesheet_directory_uri().'/hide_some_field.css');
    }
}

If you use a theme instead, change: get_stylesheet_directory_uri() by get_template_directory_uri().

Another similar alternative without a css file is:

add_action('admin_init', 'ts_hiding_some_fields');
function ts_hiding_some_fields(){
    // your 2 pages in this array
    $arr = array(23, 143);
    if(get_post_type() == 'page' && !in_array(get_the_ID(), $arr))
    {
        echo '<style type="text/css">
        #wpcf-post-relationship {display: none;}
        </style>';
    }
}

I havent tested all this but it should work.

Comments