Force FacetWP to re-index with PHP

If you are programmatically adding posts to WordPress and using FacetWP, when you add a new post you must force FacetWP to re-index.

If a post is added in the admin, FacetWP does this for you. However if you add posts with code, you need to fire a re-index.

You can do this with the code below.

This example, re-indexes a specific post, the new post ID is taken from the post just created.

In this example, my function (hd_reset_job_facets) is hooked into a action that fires after our post is created.

You would need to hook into whatever hook is appropriate that runs once your post is added.

<?php
/**
 * Re-indexes FacetWP when a new job arrives.
 *
 * @param integer $job_post_id     The newly created job post id.
 * @param array   $job_data        The array of job data sent from the multi poster.
 */
function hd_reset_job_facets( $job_post_id, $job_data ) {

	// if facetwp is active.
	if ( function_exists( 'FWP' ) ) {

		// run the indexer for the newly created job post.
		FWP()->indexer->index( absint( $job_post_id ) );

	}

}

add_action( 'jobrelay_wpcon_job_inserted_complete', 'hd_reset_job_facets', 30, 3 );