[wp-hackers] Question about do_action & its handling of arguments

Claude Needham gxxaxx at gmail.com
Wed Jul 27 18:46:25 UTC 2011


Very generous reply.
Thank you.
I'm good to go.
Regards,
Claude

On Wed, Jul 27, 2011 at 11:17 AM, Otto <otto at ottodestruct.com> wrote:
> On Wed, Jul 27, 2011 at 12:41 PM, Claude Needham <gxxaxx at gmail.com> wrote:
>> On Wed, Jul 27, 2011 at 10:13 AM, Otto <otto at ottodestruct.com> wrote:
>> Quite helpful.
>> That helps explain the reason for the code.
>>
>> I was wondering though, what is the best way to handle a situation such as this.
>>
>> $categories = get_the_category();
>> do_action('gxxaxx_getbestcategory', $categories);
>>
>> function gxxaxx_getbestcategory($categories) {
>>
>>        foreach($categories as $category) {
>>                do something with $category->slug;
>>        }
>> }
>>
>> If the post has more than one category this code works fine.
>> If the post has only one category then the code fails.
>
>
> Several possible workarounds.
>
> One, check for the object case and adjust it properly.
>
> if ( is_object($categories) )
>         $categories = array($categories);
> foreach($categories as $category) {
>         do something with $category->slug;
> }
>
> Two, pass in an extra argument to avoid the casting case.
>
> do_action('whatever',$categories,1);
> add_action('whatever','functionname',10,2);
>
> Three, pass something other than the categories to begin with.
>
> do_action('whatever',$post->ID);
> add_action('whatever','xxx',1);
> function xxx($id) {
>  $cats = get_the_category($id);
>  ...
> }
>
> -Otto
> _______________________________________________
> 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