How to include meta keywords on dynamically created page in WordPress?

62 Views Asked by At

Using a single service page, I have created 50 location based service page dynamically. I dont know how to add meta keywords for each location based pages dynamically.

I used arrays to display the location name on content using short code functionality. Below you can find the code, which I'm using now.

Below is the array

$STATES_ARRAY   = array(

array(
    "slugCode"=> "florida",
    "name"=> "Florida",
    "stateCode"=> "FL", 
    "plans"=> "plan 1, plan 2"
    ),
    array(
    "slugCode"=> "georgia",
    "name"=> "Georgia",
    "stateCode"=> "GA", 
    "plans"=> "plan 1, plan 2"
    ),
);
define('STATES_ARRAY', $STATES_ARRAY);

Below is the short code function

function mp_usstate_name_shortcode() {

            $usstate_name = "";
            $chosen_state = [];
            global $STATES_ARRAY;           
            $state = array_filter($STATES_ARRAY, function($state) {
                return $state["slugCode"] === get_query_var("usstate");
            });

           if(count($state) > 0){
            $chosen_state = array_pop($state);
            if(!empty($chosen_state) ){ 
                $usstate_name = $chosen_state["name"]; 
            }
          }
            return $usstate_name;
        }
        
add_shortcode('US_STATE_NAME', 'mp_usstate_name_shortcode');

Is it possible to use same set of arrays by including various meta keywords in it?? I want to add meta keywords on all my location based Page.

Right now I generated location based page for my 2 service pages. I want to include location based keywords on both service pages.

1

There are 1 best solutions below

6
Chad Phillips On

If you add to the $STATES_ARRAY a comma-separated list of keywords with key, "keywords", this code should add a keywords tag to the of the pages that has "service-page" in the slug.

function karthy_add_keywords() {
    $pageSlug = get_query_var('name');
    $isServicePage = strpos($pageSlug, 'service-page');
    if ( $isServicePage !== FALSE ) {
      global $STATES_ARRAY;           
      $state = array_filter($STATES_ARRAY, function($state) {
          return $state["slugCode"] === get_query_var("usstate");
      });
  
      if(count($state) > 0){
          $chosen_state = array_pop($state);
          if(!empty($chosen_state) && array_key_exists('keywords', $chosen_state)  ){ 
              $keywords = $chosen_state["keywords"]; 
              echo '<meta name="keywords" content="'.$keywords.'">';
          }
        }
    }
}
add_action( 'wp_head', 'karthy_add_keywords' );