web-stories-wp icon indicating copy to clipboard operation
web-stories-wp copied to clipboard

Uninstall: Improve logic of uninstall code

Open spacedmonkey opened this issue 2 years ago • 1 comments

Feature Description

Create a new interface, called PluginUninstallAware. Similar to PluginActivationAware. In Uninstall.php, just loop around all the registered services that are `PluginUninstallAware . This makes testing unistall methods easier and make easier to spot when post type / taxonomy / meta does not. have a uninstall method.

Alternatives Considered

Additional Context

spacedmonkey avatar Sep 22 '22 12:09 spacedmonkey

Example code.

In uninstall.php

PluginFactory::create()->on_plugin_uninstall();

in Taxonomy_Base

  public function on_plugin_uninstall() {
        clean_taxonomy_cache( $this->taxonomy_slug );

	$term_query = new WP_Term_Query();
	$terms      = $term_query->query(
		[
			'taxonomy'   => $this->taxonomy_slug,
			'hide_empty' => false,
		]
	);

	if ( empty( $terms ) || ! \is_array( $terms ) ) {
		return;
	}

	foreach ( $terms as $term ) {
		if ( $term instanceof WP_Term ) {
			wp_delete_term( $term->term_id, $term->taxonomy );
		}
	}
  }

In Post_Type_Base

 public function on_plugin_uninstall() {
     $cpt_posts = get_posts(
		[
			'fields'           => 'ids',
			'suppress_filters' => false,
			'post_status'      => 'any',
			'post_type'        => $this->get_slug(),
			'posts_per_page'   => - 1,
		]
	);

	foreach ( $cpt_posts as $post_id ) {
		wp_delete_post( (int) $post_id, true );
	}
 }

Base_Color

class Base_Color extends Service_Base implements HasMeta, PluginUninstallAware{
...
public function on_plugin_uninstall() {
   delete_post_meta_by_key( self::BASE_COLOR_POST_META_KEY );
}

spacedmonkey avatar Sep 22 '22 12:09 spacedmonkey