• Resolved CMTV

    (@cmtv)


    I have 3 posts. All of them are attached to 3 categories with slugs: “game-updates-patches”, “patch”, “news”. Category “patch” is a subcategory. The parent is “game-updates-patches”.

    Everything is okay in admin section:

    Now I want to check whether my post is attached to “patch” category or not.

    I use this code to do so:

    $posts_array = get_posts([
        'category' => 'game-updates-patches'
    ]);
    
    foreach($posts_array as $post) { 
    
       /* Checking! */
       if(has_category('patch', $post->ID)) {
          some_stuff...
       }
    }

    The problem is that it can’t detect the third post! This condition works fine for last two posts only!

    Here is the image of categories of the third post:

    As you can see “Патч” (which slug is patch) is checked. However, this post fails condition mentioned above. Moreover, I printed all categories of this third post using get_the_category() function and it showed only “news” category.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    These category functions use the WP_Term_Query class to do the heavy lifting. It contains a number of hooks that plugins and themes can use to alter behavior. It appears something is altering behavior when it shouldn’t be. We need to narrow down potential sources.

    Please temporarily deactivate your plugins and switch to the twentysixteen theme. Copy your category code to a theme template like single.php (after making a copy of the original template). Your code should work correctly and list that problem post.

    Switch back to your normal theme. I’m assuming your category code exists here, otherwise do the same thing with templates. Test again. Activate plugins one by one. When your code fails again, the last activated entity is at fault. You can try debugging this code, or take up the issue with the author.

    Thread Starter CMTV

    (@cmtv)

    @bcworkz, thank you. Before doing everything you suggested I decided to try changing something in my code.

    And I found solution!

    The solution was to use ‘category_name’ instead of ‘category’. I still don’t know why it was broken (perhaps the true reason lies in your answer).

    Anyway thank you for help!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Can’t get category slug programmatically’ is closed to new replies.