Search

Generic selectors
Exact matches only
Search in title
Search in content

WordPress do_shortcode with PHP if else condition

WordPress do_shortcode is the prebuilt way to display predefined widgets in PHP code. That’s a nice and useful option if you just need to reflect some widget in PHP code, but if you need to do something more like a PHP if statement condition, then things could get more complicated.

I’ve got a case when I had to display an auction widget on the site. Itself everything worked fine, but every time the widget got displayed, even though it has not got content to be displayed, it still displayed some attributes that were empty and that was not good from the appearance standpoint. Tried different approaches, but regular approaches like “if (!empty ($ widget))” or “if (isset ($widget))” didn’t work as widget still got displayed though it was empty.

WordPress do_shortcode with PHP if else statement and “strlen”

So I went ahead and started to think how else I can try to differentiate whether the widget returns an empty response or it has content that needs to be displayed. And then I realize that PHP “strlen” function might be exactly what I need. Most widgets return content in string data type, and my case is not an exception. So I decided to measure the length of the response returned in a string when the widget has no content, and I got a value of ~830 chars.

Knowing that I have created the following function with “strlen”:

<?php
// Put shortcode in a variable
$planned_auctions = do_shortcode('[yith_auction_non_started]');

// Check the size of the string returned by the variable. In my case, if more than 830, then this means that the shortcode is not empty and should be displayed
if (strlen($planned_auctions) > 830) {

    // Execute shortcode variable is it length is more than 830
    echo $planned_auctions;
} else {

    // Otherwise return nothing to display
    return;
}
?>

Summary:

By using PHP “strlen” you could check the size of the response the widget returns and based on this decision on some particular logic as in my case. That’s not considered a solid solution, though it does what is needed.

Leave a Reply

Alex Kostritsa

About author
My name is Alex. For more than 10 last years I've been worked in the role of Project Manager in an Agile environment. I have experience working with different business domains including e-commerce, social networks, and gambling. As a Software Manager, I try to keep myself tuned and continue self-development.
View all posts (18)
  • Odessa, Ukraine