Shortcode to read out specific array elements

Support General Shortcode to read out specific array elements

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #10673
    quint_rabbitquint_rabbit
    Participant

    Hi everyone - I have still not got the hang of reading out of an array.

    I have an array called "key_topic_1".
    If I use the folowing shortcode, it displays the entire array, including headings:
    [rwmb_meta meta_key="key_topic_1"]

    The array has elements "topic, obj1, obj2, ..."
    I want to use a shortcode to access the value of one specific element.

    Could the shortcode be modified to work like this?
    [rwmb_meta meta_key="key_topic_1.topic"]

    [rwmb_meta meta_key="key_topic_1.obj1"]

    Thanks in advance for any help.
    Stephen.

    PS: here is the array code from MB Builder:

    array (
              'id' => 'key_topic_1',
              'type' => 'fieldset_text',
              'name' => 'Key Topic 1',
              'desc' => 'Key Topic 1 and related Learning Objectives',
              'rows' => 2,
              'options' =>       array (
                'topic' => 'Topic',
                'obj1' => 'Learning Objective 1',
                'obj2' => 'Learning Objective 2',
                'obj3' => 'Learning Objective 3',
                'obj4' => 'Learning Objective 4',
                'obj5' => 'Learning Objective 5',
              ),
    #10675
    quint_rabbitquint_rabbit
    Participant

    Okay, I think I have done it!!
    Long trial and error.
    Please give me feedback on whether what I have done is a good idea!
    Suggestions for improvements welcome!

    I have created a new shortcode my_meta2 and I am calling it like this:
    [my_meta2 meta_key="key_topic_1" element="topic"]
    [my_meta2 meta_key="key_topic_1" element="obj1"]

    In functions.php I have added this code:

    add_action( 'init', function () {
      add_shortcode( 'my_meta2', function ( $atts ) {
        $atts   = shortcode_atts( [
          'meta_key' => '',
          'element' => '',
          'post_id'  => get_the_ID(),
        ], $atts );
        $value = rwmb_meta( $atts['meta_key'], array(), $atts['post_id'] );
    
    return $value[$atts['element']];
    } );
    } );
    #10683
    Anh TranAnh Tran
    Keymaster

    Glad that you figured it out. Nice solution!

Viewing 3 posts - 1 through 3 (of 3 total)
  • The topic ‘Shortcode to read out specific array elements’ is closed to new replies.