How to add extra javascript in head-section of only few pages

  • Anonymous

    #3211

    Since I want to add Ajax to only a couple of my WP/Graphene pages, I would like to add a few javascript functions in the head section of only those few pages.

    Is there an easy way to do so and -if yes- will that code stay after WordPress and Graphene upgrades?

    Thanks in advance!

    Anonymous

    #23903

    Is there an easy way to do so…

    Yes, you can. You’ve to use Conditional tags.

    if yes- will that code stay after WordPress and Graphene upgrades?

    They don’t stay after the update if you hack the parent theme.

    Anonymous

    #23904

    Thanks!

    Does this mean I have to copy the specific file to my child theme and add these conditional tags there? But that means that a new version of that file in the parent theme will not be used anymore because I’ve a one in my child theme. Is that right? In that case, that’s also not a solution.

    Or via the action hooks? Is there an action hook for the inside head-section of the pages?

    Thanks again!

    Anonymous

    #23905

    I try to post a few new questions in the forum, but they don’t show up… Let’s try if a respons works…

    Anonymous

    #23907

    There were example-links in my questions. That was the reason. I took them out. I’m sorry…

    Anonymous

    #23908

    The easiest way to add a custom function to your child theme. Set up your function with conditional tags (as explained by Prasanna above), include the javascript you would like to use, and hook it to the wp_head action hook.

    For example:

    function add_custom_js () {
    if (is_page( array( 42, 54, 6 ) )) {
    ?> YOUR JAVASCRIPT CODE <?php
    }
    add_action('wp_head', 'add_custom_js');

    This basically tells wordpress to include the javascript code in the head section of only pages with the ID of 42, 54, and 6.

    (Moved to support. Please post in the correct section)

    Mod

    Kenneth John Odle

    #23909

    If you need other conditional tags, see this:

    http://codex.wordpress.org/Conditional_Tags

    Anonymous

    #23910

    I’ll give it a try, thanks!

    Mod

    Kenneth John Odle

    #23911

    Just be sure that if your Javascript includes quotations marks (“), you escape them (“), else it will cause all sorts of problems with your blog.

    See this for more info about escaping:

    http://blog.kjodle.net/2011/11/04/graphene-action-hook-widgets-an-easy-way-to-modify-your-blog/#Bonus_A_Little_PHP_Goes_a_Long_Way

Viewing 9 posts - 1 through 9 (of 9 total)

You must be logged in to reply to this topic.

Do NOT follow this link or you will be banned from the site!