0

I have the following problem, i've queried the attached media to a post with:

function abc_attachments( $post_id ) {
    $query = array(
        'post_parent'       => $post_id,
        'post_type'         => 'attachment',
        'post_status'       => 'inherit',
        'post_mime_type'    => 'image',
        'numberposts'       => '-1'
        );
    $images = get_children( $query );
    return $images;
}

as a result i get an array of objects. But somehow i am unable to get the object keys transfered to a new separate array. The array of objects looks like that for example (i've left out the contained key value pairs):

Array
(
    [1074] => WP_Post Object
        (
        )

    [1067] => WP_Post Object
        (
        )
)

When i try to loop through the array of objects with foreach and write the object keys to an array i get

Catchable fatal error: Object of class WP_Post could not be converted to string

with the following snippet:

    $media = abc_attachments( $post->ID );

    foreach( $media as $key ) {
        $arrayofids .= $key . ", ";
    }
    preprint($arrayofids);

Is there a more elegant and less fatal way?

  • Wordpress is an abomination to serious coding and pathetically coded. – r3wt Mar 25 '15 at 13:34
  • $key is an object :) – Reigel Mar 25 '15 at 13:49
  • if you have just used foreach( $media as $key => $value ) then this time $key is array key you are looking for.. :) – Reigel Mar 25 '15 at 13:50
0

Ok i was a bit headblocked; with the following snippet i was able to get things working as expected:

    $media = abc_attachments( $post->ID );

    $arrayofids = array();
    foreach( $media as $key ) {
        array_push($arrayofids, $key->ID);
    }
    preprint($arrayofids);

Which lead to the following output:

Array
(
    [0] => 1072
    [1] => 1067
)
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.