Creating a portfolio or gallery using WordPress media files

One of the cool things one can do in wordpress is to create a gallery or portfolio of images using files directly from Media Library. In general after been uploaded, files in wordpress become “Attachments”. I will show you how i created a simple portfolio page using files uploaded in my media library.

I uploaded image files in Media Library as usual and them went on to edit the same. Here’s an edit screen shown below:

I created a Custom Field* by name “portfolio-projects” with a value “yes”. I will use this field to load portfolio image in my portfolio page. I placed the following code in my template file to load the portfolio image. Once can convert this code into a theme function easily to have it working using add_fileter in the_content or similar kind of approach as well.

So here’s my template code:

$portfolio = '<div id="web-portfolio">';
$args = array(
'post_type' => 'attachment',
'meta_query' => array(
array(
'key' => 'portfolio-projects',
'value' => 'yes',
)
)
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
$title = get_the_title();
$portfolio .= '<div class="portfolio">';
$imageThumbElement = wp_get_attachment_image($attachment->ID);
$imageUrl = wp_get_attachment_url($attachment->ID);
$portfolio .= '<a href="'.$imageUrl.'" title="'.$title.'">'. $imageThumbElement . '</a>';
$portfolio .= '
<div class="overlay" style="display:none;"></div>
<div class="ic_caption"> ';
$portfolio .= $attachment->post_content;
$portfolio .= '</div>
</div>';
}
}
$portfolio .= '</div>';

My example page is here.

* – You might have to use some Custom Field plugin to have an option available to add custom fields. In my case the File-Gallery plugin had been in use.

Leave a Reply