Search code examples
wordpresswordpress-shortcode

Wordpress errors from shortcodes being executed on edit page


I am writing a wordpress plugin.

I have noticed in my debug log that i get a lot of PHP errors thrown because my shortcodes are being executed on the admin edit pages and therefore the relevant data is not available because the shortcode is loading dynamic data based upon the user front end. For example i have a function:

function myFunction_availability() {
    if (is_admin()) return;   // tried adding this but still get the issue
    $product = $this->myFunction_get_current_product();
    return "<div class='product-availability'>{$product->availability}</div>";
}

Works fine from the front end, but whenever i load the edit page from admin area i get in my log:

PHP Warning:  Attempt to read property "availability" on null in /home/vagrant/yodahwp/wp-content/plugins/yodah/class.yodah.php on line 1602

As you can see from my code, i tried adding is_admin() to exit out of the function if viewing an admin page (i.e. the edit post page) but this does not seem to work.

Do any wordpress whizzes have an answer for this? I am a bit surprised that shortcodes are executed on the admin edit pages, or am I missing something?!

Thanks


Solution

  • This is an old question. Usually, this happens when using visual builders.

    One solution is to write a condition to check if the product exists.

    If using woocommerce you can try:

    $product = wc_get_product( get_the_ID() );
    if($product){
      //continue
    }
    

    In your case, you should edit your myFunction_get_current_product() method and verify there if the product exists.