• I have tried unsuccessfully to check category of Post in functions.php. I have created 3 different categories under Posts.

    I have used has_category(), in_category() and is_category() functions to check category. Those returns always default category Uncategorized. None of my Posts are not in Uncategorized category. I have testing this by creating Post and selected one category (checkbox) before publishing Post.

    What is correct way to check category of the Post? (Or what I need to check from Post?)

    • This topic was modified 3 years, 5 months ago by jarpola.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi there. Usually the check for the category is done from within the loop of whatever template is being used. For example if checking the category of a standard post you could use this from within the loop to check for a specific category:

    <?php if (in_category( 'category-slug' )) : ?>Do something here<?php endif;?>

    If you were wanting to list all categories that that post is assigned to, you would use something like this from within the loop:

    <?php
    		$categories = get_categories();
    		foreach($categories as $category) {
      		 echo '<a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a>';
    		}
    		?>
    Thread Starter jarpola

    (@jarpola)

    I faced following problem / feature in WordPress:

    Let’s assume that default category for new posts is A. When I create new post with category B, WordPress seems to save the new post to database with category A and rigth after save it changes it desired category (B).

    I need to read new post and it’s category rigth after the new post is published at the first time. Every time I publish post it’s category is default (A), regardless whatever I select. WordPress mechanism seems to be working like this.

    Hi @jarpola,

    You can try this

    <?php
    $args = array(
         'type' => 'post',
         'child_of' => 0,
         'parent' => ''
    );
    $categories = get_categories( $args );
    foreach ( $categories as $category ) { ?>
          <?php ehco $category->name ; ?>
    <?php } ?>
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Check category of Post’ is closed to new replies.