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

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #48436
    AndrewAndrew
    Participant

    Hi, 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?

    #48437
    AndrewAndrew
    Participant

    Further 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
    }
    #48440
    PeterPeter
    Moderator

    Hello Andrew,

    If you want to use the variable or a callback function and assign it to the options setting, 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

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.