Store a value in global scope after init hook is fired

I am working now on a Settings page. As I will need data about post types, taxonomies, and posts repeatedly in my setting page, I preferred to get these variables in the global scope and call them in the setting fields to minimize the database queries.

This was working well for built-in post types and taxonomies(i.e posts, pages, categories, and tags). However, neither custom post types nor custom taxonomies data can be retrieved as they are registered when the init hook fires. Here is my code snippet:

?php
//I need to get these variables after init hook is fired to get all cpt and custom taxonomies data

$current_taxonomies_names = get_taxonomies($args, 'names');
$current_post_type_names = get_post_types($args, 'names');
$query_posts = get_posts($query_args);

//The above variables shall be used repeatedly in the below function

function appearance_settings()
{

  //Adding section and fields for the settings page
  add_settings_section('structure', 'App Structure', 'structure', 'main');
  add_settings_field('post_types', __('Post Types', ''), 'post_types', 'main', 'structure');
  add_settings_field('taxonomies', __('Taxonomies', ''), 'taxonomies', 'main', 'structure');
  add_settings_field('excluded_posts', __('Excluded Posts', ''), 'excluded_posts', 'main', 'structure');
  add_settings_field('excluded_taxes', __('Excluded Taxonomies', ''), 'excluded_taxes', 'main', 'structure');
}

So is there a way to get $current_taxonomies_names, $current_post_type_names or $query_posts after the init hook is fired?

If there is no way, is there any alternative to get these variables without keeping on querying the database in every setting field callback function?

Topic filters custom-taxonomy init hooks custom-post-types Wordpress

Category Web


So after consulting on Facebook Advanced WordPress group, the advice was to create an object with setters and getters instead of using the declaring and getting variables in the global scope as shown in the code below:

class MyPlugin
{
  public $current_post_types;

  public function __construct()
  {
    add_filter('init', array($this, 'get_variables'));
  }


  public function get_variables()
  {
    $this->current_post_types = get_post_types(array(
      'public' => true,
      'show_in_rest'   => true,
    ), 'objects');
  }
}

$skeleton = new MyPlugin();

function mk_post_types()
{
  global $skeleton;
  $current_post_types = $skeleton->current_post_types;
  //remaining code below
}

This solved the issue, now I can get all custom post types in the mk_post_types function.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.