Skip to content

Add wp post meta clean-duplicates <id> <key> command #356

Description

@danielbachhuber

Feature Request

Describe your use case and the problem you are facing

It would be helpful to have a wp post meta clean-duplicates <id> <key> command to clean up duplicated post meta (key and value are the exact same).

For example, on a user's blog we somehow ended up with multiple enclosure post meta with the same value. This caused the same enclosure to be added multiple times to the RSS <item>, invalidating the feed.

Describe the solution you'd like

A command to easily clean up post meta with the same key and value.

It might even be as easy as this code!

<?php
/**
 * Cleans duplicate closures on a post.
 */

class Clean_Duplicate_Enclosures {

	/**
	 * Cleans up duplicate 'enclosure' post meta values on a post.
	 * 
	 * ## OPTIONS
	 * 
	 * <id>
	 * : ID of the post to clean.
	 * 
	 * <key>
	 * : Meta key to clean up.
	 *
	 * ## EXAMPLES
	 * 
	 *     wp post meta clean-duplicate-enclosures 1234 enclosure
	 */
	public function __invoke( $args ) {
		global $wpdb;

		list( $post_id, $key ) = $args;

		$metas = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->postmeta} WHERE meta_key=%s AND post_id=%d",
				$key,
				$post_id
			)
		);

		$uniq_enclosures = [];
		$dupe_enclosures = [];
		foreach ( $metas as $meta ) {
			if ( ! isset( $uniq_enclosures[ $meta->meta_value ] ) ) {
				$uniq_enclosures[ $meta->meta_value ] = (int) $meta->meta_id;
			} else {
				$dupe_enclosures[] = (int) $meta->meta_id;
			}
		}

		if ( count( $dupe_enclosures ) ) {
			WP_CLI::confirm(
				sprintf(
					'Are you sure you want to delete %d duplicate enclosures and keep %d valid enclosures?',
					count( $dupe_enclosures ),
					count( $uniq_enclosures )
				)
			);
			foreach( $dupe_enclosures as $meta_id ) {
				delete_metadata_by_mid( 'post', $meta_id );
				WP_CLI::log( sprintf( 'Deleted meta id %d.', $meta_id ) );
			}
			WP_CLI::success( 'Cleaned up duplicate enclosures.' );
		} else {
			WP_CLI::success(
				sprintf(
					'Nothing to clean up: found %d valid enclosures and %d duplicate enclosures.',
					count( $uniq_enclosures ),
					count( $dupe_enclosures )
				)
			);
		}
	}

}

WP_CLI::add_command( 'post meta clean-duplicate-enclosures', 'Clean_Duplicate_Enclosures' );

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions