• I’m trying to add a script only to the head of single posts (not pages, not images, nothing else, just regular single posts.

    I’ve tried several things and this is my last attempt

    /*  ADD KISSMTRICS SCRIPT TO ONLY POSTS */
     if (is_singular( 'post' )) { ?>
    <script>
    _kmq.push(['trackSubmit', '.single-post-optin', 'Filled Opt-in Form on Single Post']);
    </script>
    <?php }
    /*  END Add KISSMTRICS SCRIPT TO ONLY POSTS */

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    If you don’t want pages or attachments you must use is_single(). is_singular() allows these. Providing a ‘post’ argument can help but may not be 100% reliable because the function is just checking the term against the global $wp_query object’s ‘post_type’ query var, which is only reliable when checking for custom post types.

    Thread Starter Frank Gomez

    (@frank6tg)

    I see, found all of that very fuzzy.

    THank you, Even as it stands right now this code doesn’t work so if I change to is_single it shouldn’t work either. Do you see a problem with any of the code? (I checked syntax but I’m not a coder)

    Thread Starter Frank Gomez

    (@frank6tg)

    Do I need to create a custom function to add this to the head of every post calling an external script?

    Moderator bcworkz

    (@bcworkz)

    The PHP part is OK. I’ve no idea what _kmq is so I can’t comment on the javascript part. One thing you could be having a problem with is this script could be executed before the part that defines _kmq is loaded. You should be seeing an error message in your browser console if that were the case: '_kmq' is undefined or something like that.

    I was assuming this was simply placed in your header.php template file. That should work, but you can still have issues with loading order. In any case, while it might work, it’s not proper. The proper way to introduce scripts is to use wp_enqueue_script().

    It may seem overkill to put a single code line in an external file, but you gain the advantage of being able to specify the script that declares _kmq as a dependency to your script. WP will then ensure that dependency gets loaded before your script.

    You can still conditionally enqueue your script using is_single() so that it is not loaded unnecessarily.

    Thread Starter Frank Gomez

    (@frank6tg)

    I agree, overkill. I really want to avoid adding script to header of entire site and keep it to just blog posts (over 300 of them)> I think i have solution and will post if it works…

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Add Script ONLY to head of single posts’ is closed to new replies.