Forum Replies Created

Viewing 1 replies (of 1 total)
  • It’s working for me, thank you for your help. i did a little modification on you code. I removed the last “,” after PHD

    ‘Phd’ => ‘PHD’, –> ‘Phd’ => ‘PHD’

    So the right code for me is :

    // Add a categories to a post based on keywords in the title.
    // Modify the $title_keywords array.  Use one keyword => one category name
    // Categories MUST exist first.  The Post title keywords will match regardless of case.
    function mam_add_category ($post_id = 0) {
       if (!$post_id) return;
       $title_keywords = array ( // The keywords and the corresponding category name to add
         'Germany' => 'Germany',
         'Phd' => 'PHD'
       );
       $title = get_the_title($post_id);
       foreach ( $title_keywords as $keyword => $cat ) {
          if ( stripos($title, $keyword) !== false ) {
             $cat_id = get_cat_ID($cat);
          }
          if ($cat_id) {
             $result =  wp_set_post_terms( $post_id, $tags = $cat_id, $taxonomy = 'category', $append = true );
          }
       }
    }
    add_action('publish_post','mam_add_category');

    [Moderator Note: Please post code & markup between backticks or use the code button. Your posted code may now have been permanently damaged by the forum’s parser.]

    Next step is create a page in the back office to add keywords in the backoffice. 🙂

Viewing 1 replies (of 1 total)