WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Compare title and category of a wordpress post (6 posts)

  1. Gisha James
    Member
    Posted 4 years ago #

    Can someone help me to figure out how to compare title and category name of a wordpress post...

    For example if category name is "wordpress" and title is "Blogs with wordpress" I like to have an output "Match"

    Thank you

  2. MichaelH
    Member
    Posted 4 years ago #

    For use in the loop:

    <?php
    $cats = wp_get_post_categories($post->ID);
    if ($cats) {
      $first_cat = $cats[0];
      $category = get_category($first_cat);
      if ( strpos(strtoupper($post->post_title), strtoupper($category->name)) ) {;
        echo 'Match';
      }
    }
    ?>
  3. Gisha James
    Member
    Posted 4 years ago #

    Thank you. But here we are checking only one category, right?

    Can you please help me to find out how to check this for all categories...

  4. MichaelH
    Member
    Posted 4 years ago #

    All the categories are in the $cats array, just use foreach structure to check each element.

  5. MichaelH
    Member
    Posted 4 years ago #

    <?php
    $cats = wp_get_post_categories($post->ID);
    if ($cats) {
      foreach ($cats as $cat) {
        $category = get_category($cat);
        if ( strpos(strtoupper($post->post_title), strtoupper($category->name)) ) {;
          echo 'Match';
        }
      }
    }
    ?>
  6. Gisha James
    Member
    Posted 4 years ago #

    Thanks very much for your time.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags