Custom PHP script throws critical error ONLY when editing page

I have the following script added to functions.php in my child theme:

function getlatestfile() { 
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('wp-content/uploads/cams/'));
    foreach ($iterator as $file) {
        if ($file-isDir()) continue;
        $path = $file-getPathname();
    }
    return img src='https://mysite.url/ . $path . ' /;
}
// register shortcode
add_shortcode('getfieldimage', 'getlatestfile');

I can save the code, insert the shortcode [getfieldimage] on the page, and the page indeed displays the latest image. No complains. But when trying to edit again the page containing the shortcode, WP tells me that there's a critical error, and wants me to go to https://wordpress.org/support/article/faq-troubleshooting/ . Cannot get any helpful info there.

Topic scripts php Wordpress

Category Web


ABSPATH helps to display the page in the backend in editmode. But for the frontend, the path for the <img../> tag needs to be modified. cutprefix() function (taken from here) does the job.

This is the working solution for the front- and backend:

function getlatestfile() {

  $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator( ABSPATH . 'wp-content/uploads/cams' ));
  foreach ($iterator as $file) {
    if ($file->isDir()) continue;
    $path = $file->getPathname();
  }
  $path = cutprefix($path, '/home/username/web/mysite.url/public_html/');
  return("<img src='https://mysite.url/" . $path . "' />");
}


function cutprefix($str, $prefix){
  if (substr($str, 0, strlen($prefix)) == $prefix) {
    $str = substr($str, strlen($prefix));
  } 
  return $str;
}

Thanks to Pat J for leading me in the right direction.


When you're editing the page, you're in the directory wp-admin, and wp-admin doesn't contain wp-content (they're both children of your site's root directory).

Instead of 'wp-content/uploads/cams/', I'd recommend ABSPATH . 'wp-content/uploads/cams/' which should work wherever you might be in the WordPress environment.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.