I have 350 posts that were using a plugin-provided option stored in a meta_key ("custom_post_template", to be precise).

I want to convert these posts to assign them a specific post_format ("gallery").

I could do it one by one, but it's going to take ages (there are 4000+ posts), so i'm looking at a clever SQL query that could do that.

Right now, i have found how to retrieve the 350 posts that were using the old system:

FROM  `wp_postmeta` 
WHERE  `meta_key` LIKE  'custom_post_template'

But i don't understand where Wordpress keeps track of the post_format-to-post association. What would be the SQL query?

1 Answer 1


After much reading, i realized that it would be more easily done using the Wordpress API, so i baked out this little script. Simply add it to your theme's functions.php then run it once. When done, remove it.

function convertGalleries($test){
    $galleries = get_posts(array( 'meta_key' => 'custom_post_template', 'post_status' => array( 'any' ),'posts_per_page'=>-1 ));
        return count($galleries);
    $result = array();
    foreach($galleries as $g){
        $result[$g->ID]= set_post_format($g->ID, 'gallery' );
    return $result;

$converted = convertGalleries(false);
echo 'result: '.count($converted). ' posts converted: <pre>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.