Add post formats to categorized posts

This here site predates post formats in core, so many of my older posts are categorized with a post format but missing an actual post format. Now that I’ve switched to the lovely TwentyThirteen, I decided to fix things up.

Here’s the bit of PHP I wrote:

[sourcecode language=”php”]
global $wpdb;
$post_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type=’post’ AND post_status=’publish’;" );

$category_to_format = array(
‘asides’ => ‘aside’,
‘galleries’ => ‘gallery’,
‘photos’ => ‘photo’,
‘quotes’ => ‘quote’,
‘statuses’ => ‘status’,
‘videos’ => ‘video’
);

foreach( $post_ids as $post_id ) {
$category = array_shift( get_the_terms( $post_id, ‘category’ ) );
if ( ! get_post_format( $post_id ) && array_key_exists( $category->slug, $category_to_format ) ) {
set_post_format( $post_id, $category_to_format[$category->slug] );
echo "Changed {$post_id} to {$category_to_format[$category->slug]}n";
}
}
[/sourcecode]

wp-cli offers a quick and dirty way to execute the PHP without even creating a file:

[sourcecode language=”bash”]
wp> global $wpdb;
wp> $post_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type=’publish’ AND post_status=’publish’;" );
wp> $category_to_format = array( ‘asides’ => ‘aside’,’galleries’ => ‘gallery’,’photos’ => ‘photo’,’quotes’ => ‘quote’,’statuses’ => ‘status’,’videos’ => ‘video’ );
wp> foreach( $post_ids as $post_id ) { $category = array_shift( get_the_terms( $post_id, ‘category’ ) ); if ( ! get_post_format( $post_id ) && array_key_exists( $category->slug, $category_to_format ) ) { set_post_format( $post_id, $category_to_format[$category->slug] ); echo "Changed {$post_id} to {$category_to_format[$category->slug]}n"; } }
[/sourcecode]

Et, voila! Because I haven’t used categories for anything more than post formats, I’m also hiding them from the admin and automagically setting based on post format.

Ten points to whomever adds multiline input to wp shell.

Leave a comment

Your email address will not be published. Required fields are marked *