[wp-hackers] Question about do_action & its handling of arguments
Otto
otto at ottodestruct.com
Wed Jul 27 18:17:21 UTC 2011
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
More information about the wp-hackers
mailing list