2010-11-14 00:02
浏览 57


The code below returns an array of images that are "attached" to posts...

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => 0
$excludeImages = get_posts($args);


var_dump ($excludeImages)

//yields (a snippet of the first item of 5 in the array)

array(5){[0]=> object(stdClass)#194 (24) 
        {["ID"]=> int(46) 
         ["guid"]=> string(59) "http://localhost/mysite/wp-content/uploads/avatar.png"}

The Question: How can I extract the image filename (in this case, avatar.png) from any given array item where the pattern is always ["guid"]=> string(int) "path-to-image"?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duangou2046
    duangou2046 2010-11-14 00:11

    just use basename

    $fileName = basename($excludeImages[0]->guid);

    EDIT: As commenter above mentioned, i think you might need arrow notation instead of indexing for "guid" as in $excludeImages[0]["guid"]. I didn't notice initially that it is an object. It seems you have an array of objects, not a structured/nested array.


    点赞 评论
  • douhezhan5348
    douhezhan5348 2010-11-14 00:13

    stdClass is basically the default class for PHP (not the base!). It does not have any method or attribute, it's an empty class. It is used as a container. You can create such a class by casting an array to an object, for example.

    Your var_dump means that the first element of your array is an stdClass object having a ID and guid attributes. Therefore, this code would retrieve the full guid :

    $path = $excludeImages[0]->guid;

    If you only want to retrieve the filename, you can use basename() :

    echo basename($path); // avatar.png

    You can see this question for more information about stdClass.

    点赞 评论