[wp-hackers] get_categories() add post type to arguments?
Nathaniel Taintor
goldenapplesdesign at gmail.com
Tue Apr 2 16:43:03 UTC 2013
I understand the issue. Its one I've dealt with before, albeit awkwardly.
I agree with Mike that there's often a better way to define your data. But
in
some cases, I've explicitly wanted to use custom taxonomies to link posts in
different posts types. And it has been frustrating not being able to query
onlyterms that have posts of a given post type.
The workaround I've used is to temporarily modify the definition of the
taxonomy
I'm trying to query, making sure to reset it to its original definition
afterwards. You can do this because all the taxonomy definitions are stored
in
the global variable $wp_taxonomies:
global $wp_taxonomies;
$backed_up_tax = $wp_taxonomies['yourcustomtax'];
// Redefine the taxonomy to only apply to the post type you want to get
// terms in
$wp_taxonomies['yourcustomtax']['object_type'] = array( 'yourposttype'
);
// Now query for the terms you want. Make sure to leave 'hide_empty' =>
true.
// The generated SQL will include `wp_posts.post_type IN (
'yourposttype' )
// becasue of the taxonomy definition
$terms = get_terms( 'yourcustomtax' );
// Reset the taxonomy definition. IMPORTANT.
$wp_taxonomies['yourcustomtax'] = $backed_up_tax;
A way more in the the spirit of WordPress might be to do a regular query and
filter out the result, but this approach was quicker for me.
(Note: this is kinda pseudo-code, didn't test it, so I may have left out a
step.)
Nathaniel Taintor, Designer/Developer
*Golden Apples Design*
http://goldenapplesdesign.com
@GoldenApples | 717.434.3226
goldenapplesdesign at gmail.com
On Tue, Apr 2, 2013 at 2:45 AM, Mike Little <wordpress at zed1.com> wrote:
> On 1 April 2013 18:04, Radi Varbanov <aparoph at gmail.com> wrote:
>
> > My problem is not with taxonomies, but post types.
> > Does it make sense?
> >
> >
> Are you saying that you have post categories assigned to posts and to a
> custom post type? And that you want to use get_categories() to retrieve the
> categories for the custom post type?
>
> If so, you are probably not using them correctly. If categories apply to
> both posts and a custom post type, it doesn't make sense to request a list
> of just the ones assigned to a particular post type.
>
> And if some category terms only apply to the custom post type, then you
> probably should have created a custom taxonomy for that custom post type.
> Then get_categories() could be used to retrieve the terms for just that
> custom post type via it's custom taxonomy.
>
> Mike
> --
> Mike Little
> http://zed1.com/
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>
More information about the wp-hackers
mailing list