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'))) {
wp_enqueue_script('load_script');
}
}
addScript();
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'))) {
wp_enqueue_script('load_script');
}
}
addScript();
Share
Improve this question
edited Feb 6, 2020 at 1:54
CUH
asked Feb 6, 2020 at 1:42
CUHCUH
11 bronze badge
1 Answer
Reset to default 0Issues
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' );
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744773492a4592905.html
评论列表(0条)