1

I am using

add_action('wp_head', 'function_that_returns_js_string') 

in functions.php but it is adding the string in the header across the site. How can this be narrowed down to be only included in post pages?

0

Check the type of the queried object on the page and the post type:

function function_that_returns_js_string() {
  $obj = get_queried_object();
  $type = is_a($obj,'WP_Post');
  if (true === $type && 'post' == $obj->post_type) {
    echo 'your string';
  }
}
add_action('wp_head', 'function_that_returns_js_string');

However, I am concerned that you are inserting a script directly into the head of the page rather than enqueueing it, which is more standard practice. The same trick will work to conditionally enqueue:

function function_that_returns_js_string() {
  $obj = get_queried_object();
  $type = is_a($obj,'WP_Post');
  if (true === $type && 'post' == $obj->post_type) {
    wp_enqueue_script('jcrop');
  }
}
add_action('wp_enqueue_scripts', 'function_that_returns_js_string');

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.