У меня проблема с этим классом в административной области wordpress.Возвращаемый массив из foreach
Я хотел бы вернуть значение foreach, но, к сожалению, возвращает пустую переменную!
Если я использую print_r внутри foreach, все работает!
Можете ли вы помочь мне понять, где я ошибаюсь?
Это мой код:
class MyClass{
function __construct(){
add_action('admin_init',array($this, 'getPostType'));
}
function getPostType(){
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names';
$operator = 'and';
$post_types = get_post_types($args, $output, $operator);
$types = array();
foreach($post_types as $postype){
$types[] = array(
'value' => $postype,
);
return $types;
}
}
}
$var = new MyClass();
foreach($var->getPostType() as $type){
echo $type;
}
Заранее спасибо и извините за мой плохой английский!
Изменить
class MyClass{
function __construct(){
add_action('admin_init',array($this, 'getPostType'));
}
function getPostType(){
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names';
$operator = 'and';
$post_types = get_post_types($args, $output, $operator);
$types = array();
foreach($post_types as $postype){
$types[] = array(
'value' => $postype,
);
} return $types;
}
}
$var = new MyClass();
print_r($var->getPostType());
Я получаю это: Array()
$ post_types возвращает правильное значение.
Debug:
class MyClass{
function __construct(){
add_action('admin_init',array($this, 'getPostType'));
}
function getPostType(){
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names';
$operator = 'and';
$post_types = get_post_types($args, $output, $operator);
var_dump($post_types); // array(1) { ["book"]=> string(4) "book" }
$types = array();
foreach($post_types as $postype){
$types[] = array(
'value' => $postype,
);
var_dump($postype); // string(4) "book"
} return $types;
}
}
@ RyanVincent Я отредактировал сообщение, добавив отладку! – Danilo