1

So I was asked to add some analytics code to a sponsored post. I usually do it like this:

if(is_single('post_slug')):
// Insert analytics code;
endif;

However, I cannot figure out how to do it on a post with a custom post type.

I found this function which takes the slug of the custom post type:

is_singular('event');

My question is, is there a function that would take the custom post type and the slug of the post?

Would really appreciate your help. Thanks!

2
  • developer.wordpress.org/reference/functions/is_single "Works for any post type, except attachments and pages"
    – inarilo
    Commented Dec 12, 2017 at 11:21
  • 1
    Add a custom field to all posts of the specific type. Let them set a checkbox if the post should have analytics. After that check the value and add the analytics.
    – Martin
    Commented Dec 12, 2017 at 15:22

2 Answers 2

1

You can mix two functions:

if( is_singular( $post_type ) && is_single( $post_slug ) ):
// Insert analytics code;
endif;
0

Use shortcode!

Put this inside functions.php

// Assign the tag for our shortcode and identify the function that will run. 
add_shortcode( 'custom-analytic', 'wpse61170_custom_analytic' );

// Define function 
function wpse61170_custom_analytic() {
    ob_start();
    ?>
    //Put your analytics code here
    <?php
    return ob_get_clean();
}

In any page you want the analytics to show, just put this shortcode

[custom-analytic]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.