• Resolved Devin Price

    (@downstairsdev)


    I am trying to deregister javascripts that aren’t needed on certain pages, ala Justin Tadlock’s tutorial. The script I have works fine if I specify a specific page, but I would like it to also work on any child pages of the parent specified. Here’s the working code:

    function deregister_postTabs_addJS() {
    	if (!is_page('gallery')) {
    		wp_deregister_script( 'postTabs');
    	}
    }
    add_action( 'wp_print_scripts', 'deregister_postTabs_addJS', 200);

    Here’s how I would like it to work:

    function deregister_postTabs_addJS() {
            global $post;
    	if (!is_page('gallery') && !($post->post_parent=="3830")) {
    		wp_deregister_script( 'postTabs');
    	}
    }
    add_action( 'wp_print_scripts', 'deregister_postTabs_addJS', 200);
Viewing 1 replies (of 1 total)
  • Hey Devin,
    You might want to give my get_page_root() function a try.

    function get_page_root( $post ) {
    	if( is_object( $post ) ) {
    		if( is_array( $post->ancestors ) ) {
    			$ancestors = array_reverse( $post->ancestors );
    			if( !empty( $ancestors ) )
    				return intval( $ancestors[0] );
    			else
    				return intval( $post->ID );
    		}
    	}
    	return 0;
    }

    It accepts a WordPress post object as it’s only parameter and will always return an integer:

    1. If the page has no parent, it will return the ID property of the $post object that was passed.
    2. If the page is a descendant of any other page, it will return the ID property of it’s oldest ancestor.
    3. In every other case, it should return zero.

    With this function, the following code should do what you need:

    function deregister_postTabs_addJS() {
    	global $post;
    	$id = intval( $post->ID );
    	if( get_page_root( $post ) !== $id )
    		wp_deregister_script( 'postTabs' );
    }
    add_action( 'wp_print_scripts', 'deregister_postTabs_addJS', 200 );
Viewing 1 replies (of 1 total)
  • The topic ‘Deregister scripts if parent page == ‘gallery’’ is closed to new replies.