How to link to “most recent” document in the Media Library?

Our customer wants a “Latest Newsletter” type link on the homepage.

I figured there’d be an easy way to specify a document from the media library (perhaps by name or title) but nothing is coming up in Google.

Read More

So he’ll be uploading jan.doc, then feb.doc etc to the media library. He doesn’t want to keep overwriting the same one, as it’s neat to build up a little library of these things in his WordPress dashboard.

But I think he’d be prepared to flag or tag the latest one, or even rename the latest one each month to “Latest Newsletter” as its title in WordPress (not the filename).

But how can our theme’s header reliably link to his chosen/latest newsletter?

Related posts

1 comment

  1. You could search the latest attachments like my example below.
    I searches for the string “newsletter”, and the first time it pops up in a filename, it writes a link.
    I’ve tried to make it easy to understand.

    $attachments = get_posts( array(
        'post_type' => 'attachment',
        'posts_per_page' => 20,
        'post_status' => null,
        'post_mime_type' => 'application/pdf,application/msword'
    ) );
    
    foreach ( $attachments as $attachment ) {
        $url = wp_get_attachment_url( $attachment->ID);
        $needle = "newsletter";
        if(stripos($url, $needle) !== false){
            echo "<a href='$url'>";
            echo "Read the latest newsletter here";
            echo "</a>";
            break;
        }
    }
    

    posts_per_page sets how many attachments you want to search, so it depends on how much activity the site has got, and how far back it should look for a file matching the credentials.

    The only BUT in this is that you should have a specific string represented in every newsletter name uploaded in order for this to work.
    So newsletter_feb.doc would work in this example.

    Note that you should specify post_mime_type to match the documents your client will be uploading newsletters in. But like this it skips images, which in my experience fills up a lot of space in the media library.

Comments are closed.