How do I run a get_posts query on an individual options page for my plugin and send those results to another function to populate the select fields?
I’m building a custom plugin that builds a vcard from custom fields on various post types.
On my options page, generated by CMB2, loaded on cmb2_admin_init, I have various select fields that show meta_keys I’ve found from running a query against all post types. I am seeing a huge number in queries naturally as the entries grow inside each post type. Therefore, I only want to run that query when on the specific admin options page. That is the only time I need that query.
I have been trying to use the ‘load-{options-page.php}’ action hook which works fine, but I don’t understand how to run that query and then get the results inside the function firing on cmb2_admin_init. They are both inside a class so maybe I can pass a variable? But ti always seems to re-run the query because the variable gets assigned inside the function firing on cmb2_admin_init.
I can run this method on ‘load-[name-of-optins-page.php}’
/** * Convert to array for CMB2 field type * @since 0.1.0 */ public function get_meta_keys_array() { $ options = array(); // Get keys from a WP_Query $ fields = $ this->get_meta_keys(); if( $ fields ) { // Builds simple array to populate my select fields foreach( $ fields as $ field => $ key ) { $ options[$ key] = $ key; } } return apply_filters( 'vcard_get_meta_keys_array_output', $ options ); }
and then this function for the field display on ‘cmb2_admin_init’
/** * Registers options page menu item and form. * * @since 1.9.0 */ public function register_options_metabox() { // This is where I am running into trouble. $ meta_keys = $ this->get_meta_keys_array(); $ cmb_options = new_cmb2_box( array( 'id' => 'vcard_generator_metabox', 'title' => esc_html__( 'vCard Generator Settings', $ this->plugin_name ), 'object_types' => array( 'options-page' ) $ cmb_options->add_field( array( 'name' => esc_html__($ person['name'], $ this->plugin_name), 'id' => 'vcard_generator_metabox' . $ person['id'], 'type' => 'select', 'show_option_none' => true, 'default' => 'custom', 'options' => $ meta_keys // This is where the meta_keys are populated ) ); }
Note that these functions are truncated and will not work with copy/paste