AnsPress_Hooks::before_delete( integer $post_id )

Description #

This callback handles pre delete question actions.

Before deleting a question we have to make sure that all answers and metas are cleared. Some hooks in answer may require question data so its better to delete all answers before deleting question.

Parameters #

  • $post_id
    integer (Required) Question or answer ID.

Changelog #

VersionDescription
unknownunknown
4.1.8Delete uploaded images and anspress-images meta.
4.1.6Introduced.

Source #

File: includes/hooks.php

	public static function before_delete( $post_id ) {
		$post = ap_get_post( $post_id );

		if ( ! ap_is_cpt( $post ) ) {
			return;
		}

		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}

		// Initialize WP_Filesystem.
		if ( ! WP_Filesystem() ) {
			// Unable to initialize WP_Filesystem, handle error accordingly.
			return;
		}

		global $wp_filesystem;

		// Get anspress uploads.
		$images = get_post_meta( $post_id, 'anspress-image' );
		if ( ! empty( $images ) ) {

			// Delete all uploaded images.
			foreach ( $images as $img ) {
				$uploads = wp_upload_dir();
				$file    = $uploads['basedir'] . "/anspress-uploads/$img";

				if ( file_exists( $file ) ) {
					$wp_filesystem->delete( $file );
				}
			}
		}

		if ( 'question' === $post->post_type ) {

			/**
			 * Action triggered before deleting a question form database.
			 *
			 * At this point question are not actually deleted from database hence
			 * it will be easy to perform actions which uses mysql queries.
			 *
			 * @param integer $post_id Question id.
			 * @param WP_Post $post    Question object.
			 * @since unknown
			 */
			do_action( 'ap_before_delete_question', $post->ID, $post );

			$answers = get_posts( [ 'post_parent' => $post->ID, 'post_type' => 'answer', 'post_status' => get_post_stati() ] ); // @codingStandardsIgnoreLine

			if ( ap_opt( 'deleting_question_with_answer' ) && $answers ) {
				ap_send_json(
					array(
						'success'  => false,
						'snackbar' => array(
							'message' => esc_html__( 'Sorry, you are not allowed to delete the question permanently if there are answers available.', 'anspress-question-answer' ),
						),
					)
				);
			}

			foreach ( (array) $answers as $a ) {
				self::delete_answer( $a->ID, $a );
				wp_delete_post( $a->ID, true );
			}

			// Delete qameta.
			ap_delete_qameta( $post->ID );
		} elseif ( 'answer' === $post->post_type ) {
			self::delete_answer( $post_id, $post );
		}
	}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment