简体   繁体   中英

How to add a script to a wordpress page based on category

We recently contracted a digital marketing firm and they've given me 3 tracking scripts to add to our site: 1 for the home page, 1 for product pages and 1 for all other pages. I have the script being added to the front page and the general product page as expected, but am having a hard time adding it to the product category pages. Using is_category is not the right answer.

I'm adding them using the following code:

add_action('wp_footer','MY_FUNCTION');
function MY_FUNCTION(){
   if ( is_front_page() ){
       ?>
           <script>
             ## Adds homepage script (first script)
           </script>
<?php
   } elseif ( is_page( '7' ) ) {
       ?>
         <script>
             ## adds script 2 to the product landing page 
         </script>
    }  elseif     if ( is_category( 'MY_CATEGORY' ) ): 
       ?>
         <script>
            ## adds script 2 to product pages (they are custom post types, not woocommerce pages))
         </script>
           </script>
       <?php
 endif; 
}

For the "everything else" scripts I'm using:

if (is_front_page()){
    }
    if ( is_page( '7' ) ){
    }
    if ( is_category( 'tours' ) ){
    }
    else {
       <script>
           ## add script 3 for all other pages
       </script>
        <?php
    
    }
    endif; 
}```

Is this a good way go about adding these? 

The is_category() doesn't work for this case. What you can do instead is to get the category id and check if it is the one you need.

$cat_id = get_query_var('cat');
if ($cat_id == 5) {
//add script
}

Instead of 5 , use the category id of tours

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM