What hook should I use if I want to trigger an event after post is published?

Solved7.26K viewsWordPress
0

I’m working on an extension and would like to confirm the correct hook for triggering an event after a post has been published? Curious about both question and answer custom post types.

1
	public function after_new_question($post_id, $post) {
	    update_post_meta( $post_id, ANSPRESS_VOTE_META, '0' );
	    update_post_meta( $post_id, ANSPRESS_SUBSCRIBER_META, '0' );
	    update_post_meta( $post_id, ANSPRESS_CLOSE_META, '0' );
	    update_post_meta( $post_id, ANSPRESS_FLAG_META, '0' );
	    update_post_meta( $post_id, ANSPRESS_VIEW_META, '0' );
	    update_post_meta( $post_id, ANSPRESS_UPDATED_META, current_time( 'mysql' ) );
	    update_post_meta( $post_id, ANSPRESS_SELECTED_META, false );

		// Update answer count.
		update_post_meta( $post_id, ANSPRESS_ANS_META, '0' );

		// Update user question count meta.
	    ap_update_user_questions_count_meta( $post_id );

		/**
		 * ACTION: ap_after_new_question
		 * action triggered after inserting a question
		 * @since 0.9
		 */
		do_action( 'ap_after_new_question', $post_id, $post );
	}
	public function after_new_answer($post_id, $post) {
	    $question = get_post( $post->post_parent );

		// Set default value for meta.
		update_post_meta( $post_id, ANSPRESS_VOTE_META, '0' );

		// Set updated meta for sorting purpose.
		update_post_meta( $question->ID, ANSPRESS_UPDATED_META, current_time( 'mysql' ) );
	    update_post_meta( $post_id, ANSPRESS_UPDATED_META, current_time( 'mysql' ) );

		// Get existing answer count.
		$current_ans = ap_count_published_answers( $question->ID );

		// Update answer count.
		update_post_meta( $question->ID, ANSPRESS_ANS_META, $current_ans );
	    update_post_meta( $post_id, ANSPRESS_BEST_META, 0 );
	    ap_update_user_answers_count_meta( $post_id );

		/**
		 * ACTION: ap_after_new_answer
		 * action triggered after inserting an answer
		 * @since 0.9
		 */
		do_action( 'ap_after_new_answer', $post_id, $post );
	}

Assuming developers are not insane, ap_after_new_question and ap_after_new_answer should do exactly what you want.

It’s all in sources.

You could also use ap_processed_new_question and ap_processed_new_answer if you want your code to be executed after question or answer was added, but meta was not yet processed.
I don’t see any good reason to do it, though.

Thank you! This is exactly what I was looking for.

You are viewing 1 out of 3 answers, click here to view all answers.