Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have migrated my blog from blogspot to WordPress. Then I have noticed many of the posts contain duplicate custom fields. Like blogger_author, blogger_permalink, blogger_blog are duplicated upto 5 times. How can I remove the duplicate Custom Fields?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

You can delete directly from the database, using an SQL statement like:

delete from wp_postmeta
where meta_id in (
       select *
       from (
               select meta_id
               from wp_postmeta a
               where a.meta_key = 'blogger_blog'
               and meta_id not in (
                       select min(meta_id)
                       from wp_postmeta b
                       where b.post_id = a.post_id
                       and b.meta_key = 'blogger_blog'
               )
       ) as x
);

Don't forget to change name of the meta_key on both places if you want to delete duplicates for another custom field.

or you can use a php script for this. Example:

 <?php
define('WP_USE_THEMES', false);
require('wp-blog-header.php');

    define( 'WP_DEBUG_DISPLAY', true ); 
    ini_set( 'display_errors', true );
    $allposts = get_posts('numberposts=-1&post_type=post&post_status=any');
    $keys = array('blogger_blog', 'blogger_author', 'blogger_permalink');
    foreach ( $keys as $key ) {
        foreach( $allposts as $postinfo) {
            // Fetch array of custom field values
            $postmeta = get_post_meta($postinfo->ID, $key);

            if (!empty($postmeta) ) {
                // Delete the custom field for this post (all occurrences)
                delete_post_meta($postinfo->ID, $key);

                // Insert one and only one custom field
                update_post_meta($postinfo->ID, $key, $postmeta[0]);
            }
        }
    }
?>
share|improve this answer
add comment

It should be noted that this deletes all duplicate keys, not duplicate content. So if you have multiple custom fields with the key of "blogger_author" that are each different, only one of them will be saved. Just so you are aware.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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