WordPress.org

Ready to get started?Download WordPress

Forums

Attachments
[resolved] Cant call attachments more than once on template (2 posts)

  1. GreenGeorge
    Member
    Posted 1 year ago #

    im doing the normal call :

    <?php if ($attachments->exist()) {
    	while($attachments->get()): ?>
                  <?php echo $attachments->url(); ?>
            <?php endwhile;
    } ?>

    but when i attempt the exact same code further down the template it doesnt work...
    <?php if ($attachments->exist()) { ?> works but
    <?php while($attachments->get()): ?> doesnt

    can anybody help?

    http://wordpress.org/extend/plugins/attachments/

  2. Jonathan Christopher
    Member
    Plugin Author

    Posted 1 year ago #

    The Attachments loop works the same way the WordPress Loop does, but has other ways to do what you're looking to do.

    The first option is to just loop through the Attachments once and save the data to an array you can use as many times as you want:

    <?php
    
    // store all of Attachments' data in $my_attachments
    $my_attachments = array();
    if( $attachments->exist() )
    {
        while( $attachments->get() )
        {
            $my_attachments[] = array( 'url' => $attachments->url() );
        }
    }
    
    ?>
    <?php
    
    // loop through $my_attachments as much as you want in your template file
    if( !empty( $my_attachments ) )
    {
        foreach( $my_attachments as $my_attachment ) : ?>
            <p>URL: <?php echo $my_attachment['url']; ?></p>
        <?php endforeach;
    }
    
    // a second run through
    if( !empty( $my_attachments ) )
    {
        foreach( $my_attachments as $my_attachment ) : ?>
            <p>URL again: <?php echo $my_attachment['url']; ?></p>
        <?php endforeach;
    }
    
    ?>

    Alternatively, you can use the total number of attachments in conjunction with a for loop and retrieving a single Attachment.

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic