I try to write a plugin for WordPress, that keep into array some posts. This array it is contained inside a static property of a class.
The class is like the following:
class my_class_name
{
private static $posts = array();
public function __construct()
{
add_action('template_redirect', array($this, 'get_posts'));
}
public function get_posts()
{
$args = array(...);
$my_posts = new WP_Query($args);
$my_posts = isset($my_posts->posts) && !empty($my_posts->posts) ? $my_posts->posts : array();
my_class_name::$posts = $my_posts;
}
public static function get_posts()
{
return my_class_name::$posts;
}
public static function unset_post($item_id)
{
unset(my_class_name::$posts[$item_id]);
}
}
$class_instance = new my_class_name();
And then in my theme I have the following code:
$my_posts = my_class_name::get_posts();
if(!empty($my_posts))
{
$key = array_rand($my_posts, 1);
$post = $my_posts[$key];
my_class_name::unset_post($key); // I have try this way
unset($dynamic_banners[$key]); // as well this way too
echo "<pre>";
print_r($my_posts);
echo "</pre>";
}
But the problem is that the array with the given ID still exists in my array. Am I doing something wrong ?
Is there any solution for this situation ?
Arrays are pass-by-value in PHP, so
$my_posts
is not the same as themy_class_name::$posts
variable. You have to unset the values in it separately:Alternatively, you can do pass-by-reference by declaring
get_posts
asand then doing