Enqueue script only on child pages of custom post types

Issues

The code you shared has some issues: First of all calling a function like this won’t work on the bootstrapping process of the WordPress and can’t get necessary values where and when necessary, so the conditions might not work as you expected.

Solution: Hook the function to an appropriate hook, and wp_enqueue_scripts is such a hook to work with enqueued scripts.

You used $post->post_parent_in out of the context. post_parent_in is an attribute of the WP_Query() class, that is not available in the global $post object.

Solution: Instead, you have post_parent key with necessary values to compare with.

Try out

The following code will [technically] enqueue myscript to only on the child pages. The inline comments will guide you for what’s the purpose of certain lines. (Not thoroughly tested)

/**
 * My Custom Script for Child Pages only.
 */
function wpse357977_custom_script() {
    // If not on the detail page, bail out.
    if(! is_singular()) {
        return;
    }

    global $post;
    // If not on my Custom Post Type, bail out.
    if('mycpt' !== $post->post_type) {
        return;
    }


    // '0 !==' means only on the child pages.
    if( 0 !== $post->post_parent) {
        wp_register_script('myscript', get_template_directory_uri() .'/myscript.js', array(), 'wpse357977', true);
        wp_enqueue_script('myscript');
    }

}

add_action( 'wp_enqueue_scripts', 'wpse357977_custom_script' );