Change Suggested Phrases conditionally

The plugin provides a filter for developers to apply changes to the Suggested Phrases (beneath the search bar) on certain conditions.

You can put the function you need from below in your active themes directory into the functions.php file ( wp-content/themes/{your_theme}/functions.php )

Change phrases based on a condition

This code will allow displaying alternative keywords if the post ID is within an array of specified post IDs.

  • Change the $cpt_array variable to the post/page IDs where you want to display the alternative keywords.

  • Change the $alt_phrases variable to the keywords you want to display.

  • Change the $allow_home variable true if one of the page IDs you allowed is used as the home page.

add_filter("asp_suggested_phrases", "asp_change_sugg_phrase_cond", 10, 2);

function asp_change_sugg_phrase_cond($phrases, $sid) {
  // If the current post/page/cpt IDs is in this array
  // then the alternative phrases are displayed.
  // Change this to the post/page/cpt IDs you want
  $cpt_array = array( 1, 2, 3 );
  // The alternative phrases array. Add/remove keywords you want as alternatives.
  $alt_phrases = array(
    "alt phrase 1",
    "alt phrase 2",
    "alt phrase 3"
  );
  // Change this to true if one of the pages is the home page as well
  $allow_home = false;
  
  //-- Do NOT change anything below this line! --
  $post_id = get_the_ID();
  if ( is_home() && !$allow_home) return $phrases;
  if ( $post_id === false ) return $phrases;
  if ( in_array($post_id, $cpt_array) ) return $alt_phrases;
  return $phrases;
}

Last updated

Copyright Ernest Marcinko