Skip to content

Instantly share code, notes, and snippets.

@vyatri
Last active December 14, 2015 06:39
Show Gist options
  • Save vyatri/5044822 to your computer and use it in GitHub Desktop.
Save vyatri/5044822 to your computer and use it in GitHub Desktop.
Fat-free script to add Album functionality to your wordpress media library. The idea is to register a new taxonomy named 'album'. Simply paste album_wordpress.php script to your functions.php in your theme folder, or include this album_wordpress.php in functions.php. This is very basic. Fell free to use and modify.
<?php
/* paste this to functions.php or include */
register_taxonomy('album','attachment',
array(
'hierarchical' => true,
'label' => 'Albums',
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => 'fix_album_count',
'query_var' => true,
'rewrite' => true,
'singular_label' => 'Album',
'capabilities' => array(
'manage_terms' => 'edit_posts',
'edit_terms' => 'edit_posts',
'delete_terms' => 'edit_posts',
'assign_terms' => 'edit_posts'
)
)
);
register_taxonomy_for_object_type('album','attachment');
function fix_album_count(){
global $wpdb;
$sql = "UPDATE $wpdb->term_taxonomy tt
SET tt.count =
(SELECT count(p.ID) FROM $wpdb->term_relationships tr
LEFT JOIN $wpdb->posts p
ON (p.ID = tr.object_id AND p.post_type = 'attachment')
WHERE tr.term_taxonomy_id = tt.term_taxonomy_id)
WHERE tt.taxonomy = 'album'
";
$wpdb->query($sql);
}
// to populate the albums, simply use get_terms('album',$args) function in your template file.
// reference http://codex.wordpress.org/Function_Reference/get_terms
<?php
/* example to parse an album */
get_header();
$term = $wp_query->queried_object;
?>
<h1><?php echo $term->name; ?></h1>
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => 'inherit',
'album' => $term->slug,
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
// echo all images
echo wp_get_attachment_image( $attachment->ID );
}
} ?>
<p><?php echo $term->description; ?></p>
<?php get_footer(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment