Check for promotional products in WordPress with WooCoomerce

0

I'm building a WordPress site with WooCommerce and I want to check if there are products on sale with the shortcode, if there is a return to the title + products, if there is no product on the promotion, the some block. I had some ideas and one of them was this:

<?php
    //Produtos em promoção
    //Armazena o shortcode ( mas acredito estar errado ) 
    $produto_promocao = do_shortcode('[sale_products limit="4" columns="4" orderby="popularity" class="quick-sale" on_sale="true" ]'); 
    //Verifica se existe os produtos, se existir, exibe o titulo e os produtos por 
    //meio do shortcode, caso ao contrario, retorna vazio 
    if($produto_promocao != false){
        _e( 'Promotional Products', 'wordpress' ); //Exibe titulo
        echo $produto_promocao; //Exibe produtos
    } else { 
    return ''; //Retorna vazio
    }

?>

But it did not work and I figured N reasons for it. I imagine that I need some identifier for promotional products, or to do some other logic .. I accept constructive criticism, I'm training! I apologize beforehand if I did not train here right, I am a beginner. Hugs

    
asked by anonymous 24.11.2018 / 20:05

2 answers

0

Exactly, and in a slightly more simplified way I think it could look like this:

if(woo_have_onsale_products()) {
  echo do_shortcode('[products limit="4"  class="teste" columns="4" orderby="popularity" on_sale="true" ]');
} else {
  echo '<div>Nenhum produto em promoção no momento.</div>';
}

and the function to check for on-sale products would be:

function woo_have_onsale_products() {
  return !empty(wc_get_product_ids_on_sale());
}
    
30.11.2018 / 21:16
0

Talk to me, how are you?

So, man, if I understand you correctly, you can display your promotional products in this way below:

<?php if( woo_have_onsale_products() ) { ?>
<?php echo do_shortcode('[products limit="4"  class="teste" columns="4" orderby="popularity" on_sale="true" ]'); ?>
<?php } else { ?>
    <div>Nenhum produto em promoção no momento.</div>
<?php } ?>

If you do not find it necessary to compare with else , simply remove and leave if .

Then for your logic to work perfectly, insert this code below into the functions.php of your theme:

function woo_have_onsale_products() {

global $woocommerce;
// Get products on sale
$product_ids_on_sale = array_filter( wc_get_product_ids_on_sale() ); // woocommerce_get_product_ids_on_sale() if WC < 2.1
if( !empty( $product_ids_on_sale ) ) {
    return true;
} else {
    return false;
}

}

Take a test there and give me a go.

Take a look also at the woocommerce documentation page. There you will have several other display options to apply to your theme.

link

Thanks!

    
29.11.2018 / 13:36