Support » Plugins » Hacks » How to get category slug or ID in core functions.php

  • How can i get the category slug in core functions.php for use in the function wp_upload_dir()?

    I have tried all the following without success

    //$uploadcat =  get_the_category_by_ID(2); // works but need to find how to get ID
    	//$subdir = '/' . $id;
    	//$subdir = '/' . get_query_var('cat');
    	//$subdir = '/' . $post->ID;
    	//$subdir = '/' . $cat_ID;
    	//$subdir = '/' . get_the_ID();
    	//$subdir = '/' . the_ID();
    	//$subdir = '/' . get_the_category(); returns array, empty?
    	//$subdir = '/' . the_category();

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


    It would depend on the context from where you want the category, and category to what? In some cases it may not be available because the criteria to determine the category does not yet or never will exist.

    Please describe exactly what situation is occurring when you need the category and what that category is assigned to.

    I want to get the category for a post when uploading a file to wordpress through its normal media upload ui. For posts there is always at least one category assigned by default when you add a post even if you dont choose one yourself. So I want to find a way to access the category slug in the function I mentioned.

    Moderator bcworkz


    Yeah, that’s what I was afraid of. In a sense, this post may not yet exist if it’s a freshly created post, or at least it doesn’t have the “publish” status that seems to be in every WP query, so I’m skeptical that any of the usual get_the_category sort of functions will work even if you had a post ID.

    Fortunately, very soon after a new post is started in the editor, a draft backup version is created automatically. The ID of this draft should be available from $_POST['post_id'] when the media uploader is called. Go ahead and try using WP functions using this ID, it might work. If not, you’ll have to query for the category id in the terms_relationships table yourself.

    The other issue is depending on when the category is chosen and what transpires before the add media button is used, the currently selected category may not have been entered in the DB yet. If a particular category was very recently selected, the category associated with the post ID could still be the default uncategorized or whatever.

    To be sure the correct category is registered, the user should save the post as a draft before adding media. The process of determining the assigned category cannot be made completely idiot proof. It’s about all I can offer, I hope it works for you.

    The information you gave helped to fix this problem. Thank you very much bcworkz

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to get category slug or ID in core functions.php’ is closed to new replies.