How to use facets from another WordPress database

As a developer, it’s humbling to see all the amazing ways that people use the code you created. Jack Arturo shows how to pull one site’s facet data into a separate WordPress site.

function custom_switch_db( $value ) {
    $newdb = new wpdb( DB_USER, DB_PASS, DB_NAME, DB_HOST );
    $newval = $newdb->get_var( $newdb->prepare( "SELECT option_value FROM {$newdb->options} WHERE option_name = %s LIMIT 1", 'facetwp_settings' ) );
    return ( null !== $newval ) ? $newval : $value;
add_filter( 'option_facetwp_settings', 'custom_switch_db' );

function custom_switch_db_query( $query_args ) {
    global $wpdb, $olddb;
    $olddb = $wpdb;

    $wpdb = new wpdb( DB_USER, DB_PASS, DB_NAME, DB_HOST );

    // Clear the local DB cache before running queries on the other one

    return $query_args;
add_filter( 'facetwp_query_args', 'custom_switch_db_query' );

function render_complete( $output ) {
    global $wpdb, $olddb;
    $wpdb = $olddb;
    return $output;
add_filter( 'facetwp_render_output', 'render_complete' );

Essentially, we’re using WordPress’ wpdb class to switch the database before FacetWP does its internal processing. It then switches to the original database thereafter.