Populate a selewct list in a CPT from values set in a Settings Page
Support › MB Settings Page › Populate a selewct list in a CPT from values set in a Settings Page
- This topic has 2 replies, 2 voices, and was last updated 5 months, 3 weeks ago by
Peter.
-
AuthorPosts
-
June 13, 2025 at 8:42 AM #48436
Andrew
ParticipantHi, I have a CPT called Products. I want to have a select list in Products that has the product categories. The product categories are added via a settings page with a cloneable text field called prod cats. How do I get the values from prod cats to populate the select list field in my Products CPT?
June 13, 2025 at 9:51 AM #48437Andrew
ParticipantFurther to this I have this code that shows the select list in my product CPT but the list is empty:
add_filter( 'rwmb_meta_boxes', 'register_custom_meta_boxes' ); // Hook into Meta Box to register custom meta boxes function register_custom_meta_boxes( $meta_boxes ) { // Retrieve stored values from the settings page field $options = get_option( 'prod_cats_test', [] ); // Replace with the actual field key inside your settings page // Ensure values are correctly formatted before populating the select field if ( is_array( $options ) && !empty( $options ) ) { $formatted_options = array_combine( $options, $options ); // Convert array into key-value pairs for the select field } else { $formatted_options = []; // Fallback to an empty array to prevent errors } // Define the custom meta box for the specific post type $meta_boxes[] = [ 'title' => 'Product Categories', // Title of the meta box 'id' => 'custom_select_meta_box', // Unique ID for the meta box 'post_types' => ['product'], // Specify the post type(s) where this meta box should appear 'fields' => [ [ 'id' => 'product_cats', // Field ID for storing the selection 'name' => 'Select an Option', // Label for the select field 'type' => 'select', // Define the field type as a dropdown select box 'options' => $formatted_options, // Populate dropdown dynamically ], ], ]; return $meta_boxes; // Return the modified array of meta boxes for registration }June 13, 2025 at 11:03 PM #48440Peter
ModeratorHello Andrew,
If you want to use the variable or a callback function and assign it to the
optionssetting, please ensure it returns an array of choices. For example:$formatted_options = [ 'cat1_value' => 'Category 1 Label', 'cat2_value' => 'Category 2 Label' 'cat3_value' => 'Category 3 Label', ]You can add the code above to your code and see how it works. Following the documentation
https://docs.metabox.io/fields/select/#settings -
AuthorPosts
- You must be logged in to reply to this topic.