1

I need an if statement that checks the body tag if it has a class name of "single-product" using php? I need to echo a function in a single product page only of woocommerce of wordpress.

This is the code that I would like to show only for single product pages that uses woocommerce.php

<div id="from_product_page">
  <?php 
  $recent = new WP_Query("page_id=235"); 
  while($recent->have_posts()) : $recent->the_post();?>
    <?php the_title(); ?>
    <?php the_content(); ?>
  <?php endwhile; ?>
</div>

3 Answers 3

9

You can do something like this:--

$body_classes = get_body_class();
if(in_array('single-product', $body_classes))
{
    //Single product page
} else {
    //Other Page
}

get_body_class() will return all body classes with array...

0
0

PHP can't detect the body tag class of the current page, but you could use javascript or jquery to detect it and then trigger an ajax call to a php. You may be to use a client-server-client sequence.

<script>
if ( $('body').hasClass('single-product') ) { 
    $('#some_input').val('single-product');
}

$.getJSON( 'gAjax.php?whatever=' + $('#whatever').val(), null, function(jdata) {

var jObj = $.parseJSON(jdata);  //RETURNED DATA

...    
<script>
1
  • PS: PHP executes on the server side before the document DOM is created in the browser. Remembering that helps.
    – BarryDevSF
    Commented Mar 8, 2014 at 5:54
0

Example of conditioning

 if($your_varname == 'single-product'){  //your condition
       //your criteria
    }
3
  • hello, how to do the varname? Sorry, I'm still not good yet on php. I dont know if that varname can detect or pointing to the BODY TAG that I want to detect or check. Thanks Sagar for dropping by! Commented Mar 8, 2014 at 4:15
  • its a variable name in which you want check, its exist or not ? for ex. if (the_title()) contains then your criteria Commented Mar 8, 2014 at 4:18
  • I'm still confuse because the "single product" classname is automatically or should I say dynamically included on the page when viewing a single product page. Anyway thanks :( Commented Mar 8, 2014 at 4:25

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