Posted on

Metabox

Metabox is a suite of plugins to handle custom fields. It seems like a solid competitor for Advanced Custom Fields. There’s nothing particularly Relevanssi-unfriendly about it, since it uses custom fields to store the data and Relevanssi can read custom fields.

MB Relationships

MB Relationships is an extension to Metabox that can be used to create relationships between posts. If you are interested in indexing these related posts somehow, that does require extra steps since the relationships data is stored in a separate database table.

Let’s assume we have books (custom post type book) and each book has a number of authors (custom post type author). We want the search for an author name to return the author, but also every book the author is related to. We have this relationship with MB Relationships:

add_action( 'mb_relationships_init', function() {
    MB_Relationships_API::register( [
        'id'   => 'book-author',
        'from' => 'book',
        'to'   => 'author',
    ] );
} );

This defines a relationship from books to authors. Now, in order to index the author names for the books, we need this function on the relevanssi_content_to_index filter hook:

add_filter( 'relevanssi_content_to_index', 'rlv_link_author_to_book', 10, 2 );
function rlv_link_author_to_book( $content, $post ) {
  if ( 'book' === $post->post_type ) {
    global $wpdb;
    $table      = $wpdb->prefix . 'mb_relationships';
    $author_ids = $wpdb->get_col(
      $wpdb->prepare( "SELECT `to` FROM $table WHERE `from` = %d AND type = 'book-author'", $post->ID )
    );
    foreach ( $author_ids as $author_id ) {
      $author_post = get_post( $author_id );
      $content    .= ' ' . $author_post->post_title;
    }
  }
  return $content;
}

What this function does is to check if the post is a book post. If it’s not, nothing is done. If it is a book, Relevanssi then fetches the connected authors from the wp_mb_relationships table based on the current post ID in the from column and the right relationship type (book-author).

This gets a list of author IDs, which are then looped through, the author posts are fetched and the author titles are added to the $content variable. Here just the post title is used, but at this point, any data related to the post could be used.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *