SearchWP

Version 4 Documentation

Add Relevance Weight to ACF True/False Checkbox Fields

Advanced Custom Fields is a terrific plugin that makes customizing your site very easy. Not only does it facilitate content entry, it can also help you make management of other details easier for content managers. Utilizing both ACF and SearchWP is something many customers take advantage of!

One thing you can do is set up ACF with a checkbox field that controls whether some attribute of the current post is true or false. For example, perhaps some of your posts are considered proprietary and you’d like to ensure that those posts are given more weight when searches are performed.

See also: Advanced Custom Fields and SearchWP

Using a couple of SearchWP’s hooks that’s easily accomplished!

All hooks should be added to your custom SearchWP Customizations Plugin.

Assuming your ACF Checkbox field has a name of proprietary a bonus weight of 1000 will be added to any post that has that Advanced Custom Field True/False Checkbox ticked:

<?php
// Add Relevance Weight to ACF True/False Checkbox Fields in SearchWP.
// @link https://searchwp.com/documentation/knowledge-base/add-relevance-acf-checkbox/
add_filter( 'searchwp\query\mods', function( $mods ) {
global $wpdb;
$my_meta_key = 'proprietary'; // ACF True/False name.
$bonus_weight = 1000; // Extra weight to add when checkbox is ticked.
$mod = new \SearchWP\Mod();
$mod->set_local_table( $wpdb->postmeta );
$mod->on( 'post_id', [ 'column' => 'id' ] );
$mod->on( 'meta_key', [ 'value' => $my_meta_key ] );
$mod->weight( function( $runtime_mod ) use ( $bonus_weight ) {
$local_alias = $runtime_mod->get_local_table_alias();
return "IF({$local_alias}.meta_value+0 = 1, {$bonus_weight}, 0)";
} );
$mods[] = $mod;
return $mods;
} );

You can customize the hooks to use any ACF field name by editing line 9 with the applicable field name, and if you’d like to adjust the bonus weight that’s used you can edit line 10.