I have a problem with this class in the administrative area of wordpress.
I would like to return the value of foreach, but unfortunately returns an empty variable!
If I use the print_r inside the foreach everything works!
Can you help me to understand where I wrong?
This is my code:
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;
}
Thanks in advance and sorry for my bad English!
Change
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());
I get this: Array ( )
$post_types return a correct value.
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;
}
}
Aucun commentaire:
Enregistrer un commentaire