Wordpress Syntax Error, unexpected [

2019-02-25 05:51发布

问题:

I have a problem with a wordpress installation. When I work locally, this function works properly:

function get_images_from_media_library() {
  $args = array(
    'post_type' => 'attachment',
    'post_mime_type' =>'image',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => null, // any parent
    ); 
  $attachments = get_posts($args);
  $images = array();
  if ($attachments) {
    foreach ($attachments as $post) {
        setup_postdata($post);
        array_push($images, wp_get_attachment_image_src($post->ID, 'full')[0]);
    }
  }
  return $images;
}

This retrieves all the images attached to media on the installation and returns them in an array.

However, when I put my installation up on my remote site, I get this error when I try to use the theme that holds this function:

Parse error: syntax error, unexpected '[' in /hermes/bosoraweb133/b2623/ipg.yourdomaincom/98EMcBee/wp-content/themes/98emcbee/functions.php on line 52

Line 52 is this line inside the foreach:

array_push($images, wp_get_attachment_image_src($post->ID, 'full')[0]);

Why would I get this error on a remote site and not on a local site?

回答1:

That because you are using array dereferencing which is only available in PHP 5.4 and newer. You are using PHP 5.3 or older.

$array = wp_get_attachment_image_src($post->ID, 'full');
array_push($images, $array[0]);