Skip to content

Deleting Attached Posts Creates Error within Custom Field #57

@benbowler

Description

@benbowler

If you delete an attached post it shows an error on the parent post. I've solved the issue using hooks, code below, let me know where to add this into the plugin itself and I'll PR.

// These two function fix cmb2_attached_posts issue where a related post is deleted and causes an error to show in the WP backend

// Loop through attached posts and create attached_posts_attached_to meta value
function add_attached_to_meta_after_cmb2_save_field( $field_id, $updated, $action, $instance ) {
	$parent_id = $instance->data_to_save['post_ID'];

	if(substr( $field_id, 0, 8 ) === 'related-') {
		$posts = $instance->value;

		if(is_array($posts) && count($posts)) {
			foreach ($posts as $post_id) {
				$existing_meta = false;
				$new_meta = [];

				// Add this post id to the array meta
				// attached_posts_attached_to
				$existing_meta = get_post_meta($post_id, 'attached_posts_attached_to');

				$new_meta[] = $parent_id;

				if(is_array($existing_meta[0])) {
					$new_meta = array_unique(array_merge($existing_meta[0], $new_meta), SORT_REGULAR);
				}
				$add_meta = update_post_meta($post_id, 'attached_posts_attached_to', $new_meta);

			}
		}
	}
}

// add the action
add_action( 'cmb2_save_field', 'add_attached_to_meta_after_cmb2_save_field', 10, 4 );

function remove_related_post_attachements_meta_before_delete_post( $post_id ) {
	$attached_to = get_post_meta($post_id, 'attached_posts_attached_to');

	foreach ($attached_to[0] as $parent_post_id) {
		// Remove the item from the related arrays on that parent post
		$parent_meta = get_post_meta($parent_post_id);

		foreach ($parent_meta as $meta_key => $meta_value) {
			if(substr( $meta_key, 0, 8 ) === 'related-') {
				$parent_meta = get_post_meta($parent_post_id, $meta_key);
				$parent_meta = $parent_meta[0];

				// Remove the post_id from the post we're deleting form the attached meta array
				if (($key = array_search($post_id, $parent_meta)) !== false) {
				   unset($parent_meta[$key]);
				}
				$new_meta = update_post_meta($parent_post_id, $meta_key, $parent_meta);
			}
		}
	}
}

add_action( 'before_delete_post', 'remove_related_post_attachements_meta_before_delete_post' );

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions