Semi-new to WordPress, so apologies is this is an obvious question!

I'm trying to execute some JavaScript on a WordPress site, but only on the child pages of a specific parent page - so, I have example.com/books, and I want the script to run on example.com/books/foo, example.com/books/bar, example.com/books/wee, and so forth. I don't want it to run on example.com/books.

I know that I could just add in the script on each individual page, but I have other people editing the site who may add new book child pages, and they will not feel comfortable adding in Javascript.

Any solutions?


You don't quite cover how far you got and if you are familiar with basic of WP enqueue process.

Focusing on parent part I the basic code would go like this:

add_action( 'wp_enqueue_scripts', function () {

    if ( is_page() && in_array( $book_page_id, get_post_ancestors( get_the_id() ) ) ) {

        // enqueue stuff
} );

In your examples you only have one level and might have worked to just check post_parent of current post, but checking for ancestors is more thorough for more nested cases.


Extending Rarst answer if you are looking for using slug of books page. I have written a small function to check if it is a child page of any given page.

You can use it to enqueue JavaScript conditionally.

function wpse_228256_is_child_of($page) {
    $current_post = get_post();

    //First check if it is child of any page to skip the processing on other parent pages/posts
    if ( !empty($current_post->post_parent) ) {
        $target_page = get_page_by_path($page); //Now get the target page
        $top_parent = array_pop( get_post_ancestors( $current_post ) ); //Get the top parent
        if (isset($target_page->ID) && $target_page->ID == $top_parent) {
            return TRUE;

    return FALSE; //Return false for everything else 

Now you can use it to enqueue your script on child page of a given parent page.


if (wpse_228256_is_child_of('books')) {
    add_action('wp_enqueue_scripts', function() {
        wp_enqueue_script($handle, $src, $deps, $ver, $in_footer);

OR if you don't have js file and just want to print few lines in head

if (wpse_228256_is_child_of('books')) {
    add_action('wp_head', function(){ ?>
        <script type="text/javascript">
            alert('I am child page of books');

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.