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;
		}

		// 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 ) ) {
					unlink( $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' ] ); // @codingStandardsIgnoreLine

			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