How to add category name in title if not present in post title

In single,php, I’m trying to automatically add the category name to the title tag if the category name is NOT already part of the post title. Otherwise, just don’t add anything.
Here’s what I’ve tried using preg_match with no luck.

<?php
$keywords = array('Category phrase a', 'Category phrase b');
foreach($keywords as $word)
{
    if(preg_match('/'.$word.'/i', 'wp_title', 'return=true')) {
echo "";
} else {
echo "Category Phrase";
} 
}
?>

Any ideas?

Read More

UPDATE: so I somewhat figured it out but the array matching isn’t working quite right:

$keywords = array('Test word', 'Test word more');
$issouttxt = "Category Phrase: ";
$isstitle = wp_title('',false,'right'); 
foreach($keywords as $word)
{ if(preg_match('/'.$word.'/i', $isstitle)) {
$issout = '';
} else {
$issout = $issouttxt;
}}
print $issout; 

For example, if the WP title contains “Test word” it doesn’t recognize the match and $issout = $issouttxt (ie, it incorrectly adds the category name). If I remove the second part of the array (‘Test word more’), it DOES recognize the match and $issout = ”;.

Is there a different way to setup the array such that all keywords get matched and they don’t interfere with each other?

Related posts

Leave a Reply

1 comment

  1. If you’re in the loop, then I’d run it something like this. If you’re not in the loop, then you can add the post ID to the calls for the title and categories.

    This script will add all the missing categories to the title.

    <?php
    $title=get_the_title();
    $categories=get_the_category(); // or use get_categories() for all categories
    
      if(!empty($categories)) :
        foreach($categories as $category) :
          if(strpos($title,$category->name)===false)
            $title.=', '.$category->name;
        endforeach;
      endif;
     echo $title;
    ?>