| @@ -37,8 +37,64 @@ | ||
| 37 | 37 | |
| 38 | 38 | // Register REST API routes. |
| 39 | 39 | add_action( 'rest_api_init', array( $this, 'register_routes' ) ); |
| 40 | 40 | |
| 41 | + // Delete duplicate Post Meta rows before WordPress updates them. | |
| 42 | + add_filter( 'update_post_metadata', array( $this, 'maybe_delete_duplicate_post_meta' ), 10, 5 ); | |
| 43 | + | |
| 44 | + } | |
| 45 | + | |
| 46 | + /** | |
| 47 | + * Deletes duplicate Post Meta rows for the Plugin's Post Meta key, before WordPress updates them, | |
| 48 | + * which have been created by third party Plugins, migrations, or other code. | |
| 49 | + * | |
| 50 | + * @since 3.4.5 | |
| 51 | + * | |
| 52 | + * @param null $check Whether to short circuit the update. | |
| 53 | + * @param int $post_id Post ID. | |
| 54 | + * @param string $meta_key Meta key. | |
| 55 | + * @param mixed $meta_value Meta value. | |
| 56 | + * @param mixed $prev_value Previous meta value to update. | |
| 57 | + * @return null|bool Whether to short circuit the update. | |
| 58 | + */ | |
| 59 | + public function maybe_delete_duplicate_post_meta( $check, $post_id, $meta_key, $meta_value, $prev_value ) { | |
| 60 | + | |
| 61 | + // Bail if this isn't the Plugin's Post Meta key. | |
| 62 | + if ( $meta_key !== ConvertKit_Post::POST_META_KEY ) { | |
| 63 | + return $check; | |
| 64 | + } | |
| 65 | + | |
| 66 | + // Bail if a previous value is specified, as WordPress will only update matching rows. | |
| 67 | + if ( ! empty( $prev_value ) ) { | |
| 68 | + return $check; | |
| 69 | + } | |
| 70 | + | |
| 71 | + // Bail if no duplicate rows exist. | |
| 72 | + $convertkit_post = new ConvertKit_Post( $post_id ); | |
| 73 | + $rows = $convertkit_post->get_meta_rows(); | |
| 74 | + if ( count( $rows ) < 2 ) { | |
| 75 | + return $check; | |
| 76 | + } | |
| 77 | + | |
| 78 | + // Delete all but the most recent row. | |
| 79 | + $row = array_pop( $rows ); | |
| 80 | + foreach ( $rows as $duplicate_row ) { | |
| 81 | + delete_metadata_by_mid( 'post', $duplicate_row->meta_id ); | |
| 82 | + } | |
| 83 | + | |
| 84 | + // Restore the Post in the Member Content cache, as deleting the above rows removed it. | |
| 85 | + $value = maybe_unserialize( $row->meta_value ); | |
| 86 | + WP_ConvertKit()->get_class( 'restrict_content_cache' )->on_meta_change( 0, $post_id, $meta_key, $value ); | |
| 87 | + | |
| 88 | + // If the remaining row already holds the value WordPress is about to store, tell WordPress | |
| 89 | + // the update succeeded, as there's nothing to change. Without this, WordPress' own check for | |
| 90 | + // a single unchanged row returns false, and the block editor still cannot save the Post. | |
| 91 | + if ( $value === $meta_value ) { | |
| 92 | + return true; | |
| 93 | + } | |
| 94 | + | |
| 95 | + return $check; | |
| 96 | + | |
| 41 | 97 | } |
| 42 | 98 | |
| 43 | 99 | /** |
| 44 | 100 | * Register REST API routes. |