How to index and search custom fields stored in custom tables ?

951 views November 30, 2016 February 10, 2017 admin 1

The problem

Let say you’re using a plugin that does not store it’s post fields in custom fields meta.
But you’d like to filter those fields, sort them, translate them, as WPSOLR does for all other custom fields.

For instance, WooCommerce product attributes and variations are stored in a custom table. The solution described below is used internally by the WPSOLR PRO WooCommerce pack to index and search them, as if they were plain custom fields of the product custom type.

The solution

As usual in WordPress, the salvation comes from code filters. And WPSOLR comes with plenty of them.

1) Make your fields appear in the list of indexed field definitions

Use the filter Options Custom fields to add your field to the list:

array_push( $custom_fields, 'my_price' );
array_push( $custom_fields, 'my_multi_value_text' );
array_push( $custom_fields, 'my_sortable_text' );
array_push( $custom_fields, 'my_sortable_date' );

2) Select a type for your fields in screen 2.2

For field ‘my_price’, select ‘Float number’.
For field ‘my_multi_value_text’, select ‘Text, multi valued, not sortable’.
For field ‘my_sortable_text’, select ‘Text, sortable’.
For field ‘my_sortable_date’, select ‘Date, sortable’.

3) Fill your field with the post content

For that, use the filter Index custom fields:

$solarium_document_for_update[ 'my_price_f' ] = 10.2;
$solarium_document_for_update[ 'my_multi_value_text_str' ] = array('blue', 'red');
$solarium_document_for_update[ 'my_sortable_text_s' ] = 'red';
$solarium_document_for_update[ 'my_sortable_date_dt' ] = (any date here);


With a few lines of code, you were able to add your plugin field definitions and content in WPSOLR.
Now, you can search, filter, sort, those fields as if they were standard custom fields.

Was this helpful?

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.