phparrayswordpresssorting

Sort WordPress posts


I have some code in WordPress that gets the images that are attached to a specific post.
It puts all the information of that post in to an array then pulls the images from it using the built in WordPress function wp_get_attachment_image()

I then use a foreach loop to display the images in an image slider. The problem I have is that it is putting 'image1' in position 1 of the array, and 'image2' in position 0 of the array.
So it's displaying image 2 first.

here's my code.

    $args = array(
      'post_type' => 'attachment',
      'numberposts' => -1,
      'post_status' => null,
      'post_parent' => $post->ID
     );
     
    $attachments = get_posts( $args );          
    $images = array($attachments);
    echo '<div id="postSlider"><div class="slides_container">';
    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
        echo '<div>' . wp_get_attachment_image($attachment->ID, 'large') . '</div>';
        }

        echo '</div>';
        if(sizeof($attachments) > 1) {
            echo '<div class="sliderControls">
            <a href="#" class="sliderBtnPrev">Previous</a>
            <a href="#" class="sliderBtnNext">Next</a>
            <span class="sliderPagination">1 of 3</span>
            </div>';
        }
    }   
    echo '</div>';

From what I've read the foreach loop will preserve the order of the array. So, I'm thinking I need to change the order of the array so that the loop sees 'image1' (array position [1]) first.


Solution

  • If you want to change the order programmatically, have a look at the various array sorting functions in PHP, especially

    but for wordpress checkout this http://codex.wordpress.org/Template_Tags/get_posts