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

Claude Needham gxxaxx at gmail.com
Wed Jul 27 17:41:31 UTC 2011


On Wed, Jul 27, 2011 at 10:13 AM, Otto <otto at ottodestruct.com> wrote:
> This is to work around a PHP issue.
>
> If the argument being passed into the function is an array with an
> single object in it, then that if statement pulls the object out and
> that's the argument.
>
> Objects can get cast into arrays quite easily in PHP. This is
> basically to prevent that from happening.
>
> So if some code calls do_action('whatever',array(&$this)), then what
> the action functions will receive is the object $this, not an
> array($this).
>
> -Otto

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.

Do folks normally test on count?

if (count($categories) == 1) {
	do something with $categories->slug;
} else {
	foreach($categories as $category) {
		do something with $category->slug;
	}
}

This works for me. But, it seems like I'm missing some obvious php
thing that would be more standard.

I'm trying to convert my writing style to fit wp best practices so
that I can better learn wp and my code could better integrate into the
wp community.

Thanks again,
Claude


More information about the wp-hackers mailing list