I want to enqueue a script on the child pages of two different custom post types. The custom post types are named "Foods" with post id of 10000, and the other is named "Drinks" with a post ID of 20000. The child pages have a slug of /food/ and /drink/ while the parents have the slug /foods/ and /drinks/.

The code I have in my functions.php file is the following, but it is showing the script on all pages instead of just the child pages of the custom post types. What am I doing incorrectly?

function addScript() {
  global $post;

  if ($post->post_parent_in(array('10000','20000'))) {




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()) {

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

    // '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);


add_action( 'wp_enqueue_scripts', 'wpse357977_custom_script' );

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.