Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

WordPress Admin error caused by custom code

I am experiencing an error caused by a custom piece of code.  It is to show related products.  The error is found in the logs and it is effecting the Admin when you edit a page and save.  The following is the error from the log:
> Error Details
> =============
> An error of type E_ERROR was caused in line 28 of the file
> /nas/content/live/swiftstagingne/wp-content/themes/Avada-Child-Theme/t
> emplates/shortcodes/swift-cross-sell.php. Error message: Uncaught
> Error: Call to a member function have_posts() on null in
> /nas/content/live/swiftstagingne/wp-content/themes/Avada-Child-Theme/t
> emplates/shortcodes/swift-cross-sell.php:28
> Stack trace:
> #0
> /nas/content/live/swiftstagingne/wp-content/themes/Avada-Child-Theme/c
> ustom_shortcodes.php(18): include()
> #1 /nas/content/live/swiftstagingne/wp-includes/shortcodes.php(325):
> swift_cross_sell(Array, '', 'swift-cross-sel...')
> #2 [internal function]: do_shortcode_tag(Array)
> #3 /nas/content/live/swiftstagingne/wp-includes/shortcodes.php(199):
> preg_replace_callback('/\\[(\\[?)(swift\\...', 'do_shortcode_ta...',
> '[fusion_text co...')
> #4
> /nas/content/live/swiftstagingne/wp-content/plugins/fusion-builder/sho
> rtcodes/fusion-column-inner.php(549): do_shortcode('[fusion_text
> co...')
> #5 /nas/content/live/swiftstagingne/wp-includes/shortcodes.php(325):
> FusionSC_ColumnInner->render(Array, '[fusion_text co...',
> 'fusion_builder_...')
> #6 [internal function]: do_shortcode_tag(Array)
> #7 /nas/content/live/swiftstagingne/wp-includes/shor


This is the code:
<?php
$shortcodeId = 'swift-cross-sell item-' . random_int(9999, 99999999);
$skus = explode(",", $atts['skus']);

if( !is_admin() ){
  $cacheKey = 'key_products_' . implode('_', $skus);
  $loopData = WC()->session->get( $cacheKey );
  if ( empty($loopData) ) {
    $args = [
      'post_type'  => ['product', 'product_variation'],
      'meta_query' => array(
        [
          'key'   => '_sku',
          'value' => $skus,
          'compare' => 'IN',
        ],
      )
    ];
    if ( ! empty( $atts['tag'] ) ) {
      $args['product_cat'] = $atts['tag'];
    }
    $loopData = new WP_Query( $args );
    WC()->session->set( $cacheKey , $loopData );
  }
}

$loop = [];
while ( $loopData->have_posts() ) {
  $loopData->the_post();
  $productId = get_the_ID();
  if( !is_admin() ){
    $cacheKey = 'cachekey_product_data_' . $productId;
    $prodData = WC()->session->get( $cacheKey );
    if ( TRUE ) {
    // if ( empty($prodData) ) {
      global $product;
      $has_page = FALSE;
      $page = NULL;
      $link = NULL;
      $title = get_the_title();
      $custom_link_page_ID = get_post_meta( get_the_ID(), 'custom_link_page_ID', true );
      if ( ! empty( $custom_link_page_ID ) ) {
        $has_page = true;
        $page = get_post( $custom_link_page_ID );
        $link = get_permalink( $custom_link_page_ID );
      }
      $prodSku = $product->get_sku();
      $prodData = [
        'productClass' => implode(' ', wc_get_product_class('product')),
        'isVisible' => $product->is_visible(),
        'custom_link_page_ID' => $custom_link_page_ID,
        'sku' => $prodSku,
        'has_page' => $has_page,
        'page' => $page,
        'link' => $link,
        'title' => $title,
        'price' => $product->get_price_html(),
        'ID' => $product->get_id(),
      ];
      WC()->session->set( $cacheKey , $prodData );
    }
  }
  $loop[$prodSku] = $prodData;
}
// order by shortcde SKU
$sortedLoop = [];
foreach ($skus as $sku) {
  foreach ($loop as $itemSku => $item) {
    if (trim($itemSku) == trim($sku)) {
      $sortedLoop[] = $item;
      break;
    }
  }
}

?>

Open in new window

Avatar of David Favor
David Favor
Flag of United States of America image

If this is custom code from another developer, push back on them to fix their code.

If this is custom code you wrote, then you'll start at the top of the errors (first one), fixing errors one at a time, till they're all fixed.

Trying to debug custom code, requires having a copy of 100% of the code to debug + can take a long time for someone new to learn, then fix.
Avatar of Robert Granlund

ASKER

That developer is gone.
Its this line: while ( $loopData->have_posts() ) {
Call to function have_post is what is causing it.

Any suggestions on how to start fixing it?
Simple answer is have_posts() resides in WordPress core, so this function being missing suggests load order of files is somehow incorrect.

So fix is to reorder calls to follow WordPress docs.

Only someone with full access to the entire code base can determine how to fix file load order problems.
ASKER CERTIFIED SOLUTION
Avatar of Scott Fell
Scott Fell
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I believe the error appeared due to a theme update.  This info is really helpful!
If you did a theme update + problem occurred, best option is to switch to using the Avada parent theme.

If the Parent theme works, then the likely problem is your Parent theme behavior your Child theme depends on has changed slightly.

Although this seem unlikely, as have_posts() is part of core, which still points back to your Child theme file load order being the problem.

Specifically, have_posts() will be defined loading the normal wp-includes/* files, so somehow some (or more likely all) wp-includes/* files aren't being loaded before have_posts() is called.
Actually, If I remove  if( !is_admin() ){
everything speeds up, it also passes the PageSpeed test.

Can you shed some light on why that would be?  If it is only checking to see if you are a logged in admin why would it slow that down so much?

I am not that familiar with the underlying code base to give a very good answer https://developer.wordpress.org/reference/functions/is_admin/ 

There may be some issues because of the theme which I believe is very large?