Skip to content

Instantly share code, notes, and snippets.

@djrmom
Created February 8, 2018 14:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save djrmom/dda751819dc238a51a484bea4ba74240 to your computer and use it in GitHub Desktop.
Save djrmom/dda751819dc238a51a484bea4ba74240 to your computer and use it in GitHub Desktop.
facetwp index a field in a related post type
<?php
/**
** look up and index a value from a post relationship field
** set the datasource to the relationship field
** get the post id of that related post and use it to
** lookup its associated value
** for ACF you may want get_field() instead of get_post_meta()
** remember to do a full re-index after adding code
** check the wp_facetwp_index table if needed to see what values are being indexed
**/
add_filter( 'facetwp_index_row', function( $params, $class ) {
if ( 'my_facet' == $params['facet_name'] ) { // change my_facet to name of your facet
$related_post_id = $params['facet_value']; // depnding on how your relationship field saves its data this might need to be changed or looked up from a different value
$params['facet_display_value'] = get_post_meta( $related_post_id, 'some_custom_field', true ); // lookup custom field
$params['facet_value'] = $params['facet_display_value'];
}
return $params;
}, 10, 2 );
@kpstraus
Copy link

This works for my Pods relationship field!

add_filter( 'facetwp_index_row', function( $params, $class ) {
if ( 'subject' == $params['facet_name'] ) { // change 'subject' to name of your facet
    $related_post_id = $params['facet_value']['ID']; 
    $params['facet_display_value'] = get_the_title( $related_post_id ); // lookup custom field 
    $params['facet_value'] = $params['facet_display_value'];
  }
  return $params;
}, 10, 2 );

@kpstraus
Copy link

If more than one Pods relationship field:

if ( 'subject' == $params['facet_name'] || 'otherfacet' == $params['facet_name'] ) { 

Or, make an array:

$fields = array( 'subject', 'another_facet', 'some_other_facet' );
if ( in_array( $params['facet_name'] , $fields ) ) {

Replace 'subject', 'otherfacet' and 'some_other_facet' with your own facet names.

@sc0ttkclark
Copy link

I'm curious why the facet_display_value and facet_value are the same in these examples, instead of facet_value storing the ID?

@sc0ttkclark
Copy link

There's now an official add-on that we've collaborated with FacetWP on:
https://github.com/FacetWP/facetwp-pods

It covers relationship fields and all other pod fields :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment