Bug: Settings not available for custom fields

Support MB Settings Page Bug: Settings not available for custom fieldsResolved

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #29603
    GregGreg
    Participant

    Bewilderingly, the values of a settings page are not available using rwmb_meta() at the time rwmb_meta_boxes filter runs. This means that a custom field cannot be populated by a callback that gets values from the settings page using rwmb_meta().

    For example:

    
    add_filter( 'rwmb_meta_boxes', 'brkthru_post_author_metabox' );
    function brkthru_post_author_metabox( $meta_boxes ) {
        $meta_boxes[] = [
            'title'   => __( 'Post Author', 'brkthru' ),
            'id'      => 'brkthru_author',
            'context' => 'side',
            'class'   => 'brkthru-author',
            'fields'  => [
                [
                    'name'    => __( 'Custom Author', 'brkthru' ),
                    'id'      => 'brkthru_post_author',
                    'type'    => 'select',
                    'options' => brkthru_authors_array(),
                ],
            ],
        ];
        return $meta_boxes;
    }
    
    function brkthru_authors_array() {
        $authors = rwmb_meta( 'brkthru_authors', [ 'object_type' => 'setting' ], 'brkthru_settings' );
        $authors = array_column( $authors, 'author_name' );
        return $authors;
    }
    

    $authors is false in brkthru_authors_array() when the code runs inside brkthru_post_author_metabox(), but it works just fine if used elsewhere on the page.

    I have resorted to using get_option() as a workaround.

    
    function brkthru_authors_array() {
        // rwmb_meta() does not work here
        $settings = get_option( 'brkthru_settings' );
        $field_id = 'brkthru_authors';
        if ( isset( $settings[ $field_id ] ) ) {
            $authors = $settings[ $field_id ];
            $authors = array_column( $authors, 'author_name' );
            return $authors;
        }
        return array();
    }
    
    #29610
    Long NguyenLong Nguyen
    Moderator

    Hi,

    Because the helper function rwmb_meta() runs after the filter hook rwmb_meta_boxes so it does not work with the callback function. You can use the function get_option() to get settings page value inside the function callback.

    Refer to this topic https://support.metabox.io/topic/code-not-working-with-updated-version/

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