Skip to content

Instantly share code, notes, and snippets.

@trey8611
Last active December 22, 2021 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trey8611/cdf8e967668a7d27ffca1d9f507b945d to your computer and use it in GitHub Desktop.
Save trey8611/cdf8e967668a7d27ffca1d9f507b945d to your computer and use it in GitHub Desktop.
[Custom Product Imported Webhook] Adds "Product Imported" as a new WooCommerce webhook #wp-all-import #woocommerce

This adds a webhook to WooCommerce that fires when a product is newly created via WP All Import. It is currently barely tested and may need adjusted for production sites. Note that the code needs to be saved in your child theme's functions.php file, or in a code snippets plugin.

Hat tip to this thread for the code inspiration: https://gist.github.com/jessepearson/66a0e72706b99c15b52dee7ce59e1d31.

if ( ! function_exists( 'wpai_add_custom_webhook_filters_and_actions' ) && ! function_exists( 'wpai_add_custom_webhook_topic' ) && ! function_exists( 'wpai_add_custom_product_imported_event' ) && ! function_exists( 'wpai_add_custom_webhook_topics_admin_menu' ) && ! function_exists( 'wpai_add_product_imported_callback' ) ) {

	function wpai_add_custom_webhook_filters_and_actions() {
		add_filter( 'woocommerce_webhook_topic_hooks', 'wpai_add_custom_webhook_topic', 30, 2 );
		add_filter( 'woocommerce_valid_webhook_events', 'wpai_add_custom_product_imported_event', 20, 1 );
		add_filter( 'woocommerce_webhook_topics' , 'wpai_add_custom_webhook_topics_admin_menu', 20, 1 );
		add_action( 'pmxi_saved_post', 'wpai_add_product_imported_callback', 10, 3 );
	}
	
	function wpai_add_custom_webhook_topic( $topic_hooks, $webhook ) {
		switch ( $webhook->get_resource() ) {
			case 'product':
				$topic_hooks = apply_filters( 'woocommerce_wpai_webhook_topics', array(
					'product.imported' => array(
						'wpai_webhook_product_imported'
					), $webhook ) );
				break;
		}
	
		return $topic_hooks;
	}
	
	function wpai_add_custom_webhook_topics_admin_menu( $topics ) {
	
		$front_end_topics = array(
			'product.imported'  => __( 'Product Imported', 'wp-all-import' )
		);
	
		return array_merge( $topics, $front_end_topics );
	}

	function wpai_add_custom_product_imported_event( $events ) {
		$events[] = 'imported';
	
		return $events;
	}
	
	function wpai_add_product_imported_callback( $id, $xml, $is_update ) {
		if ( ! $is_update && 'product' == wp_all_import_get_import_post_type() ) {
			do_action( 'wpai_webhook_product_imported', $id );
			wc_webhook_execute_queue();
		}
	}
	
	wpai_add_custom_webhook_filters_and_actions();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment