FacetWP – add data source for WooCommerce featured products

<?php

/**
 * Add the new "Featured" Data Source within the WooCommerce heading
 */
add_filter( 'facetwp_facet_sources', function( $sources ) {
    $sources['woocommerce']['choices']['woo/featured'] = __( 'Featured' );
    return $sources;
}, 20 );


/**
 * Index the featured products
 * Note: set the facet type to "Checkboxes" and the data source to "Featured"
 * then save and re-index
 */
add_filter( 'facetwp_indexer_post_facet', function( $return, $params ) {
    $facet = $params['facet'];
    $defaults = $params['defaults'];
    $source = isset( $facet['source'] ) ? $facet['source'] : '';

    if ( 'woo/featured' == $source ) {
        $current_id = (int) $defaults['post_id'];
        $all_featured_ids = wc_get_featured_product_ids();
        if ( in_array( $current_id, $all_featured_ids ) ) {
            $defaults['facet_value'] = 1;
            $defaults['facet_display_value'] = __( 'Is Featured' );
            FWP()->indexer->index_row( $defaults );
        }
        $return = true;
    }

    return $return;
}, 10, 2 );