WordPress: Calling a shortcode for a value in a different shortcode

前端 未结 2 801
北恋
北恋 2021-01-28 18:57

I\'m very new to this, so please go easy on me if this is a dumb question.

I am building a site with events manager and geo my WordPress plugins. I want a user to be abl

2条回答
  •  清歌不尽
    2021-01-28 19:54

    As @Jeppe mentioned, you can do Nested Shortcodes:

    [shortcode_1][shortcode_2][/shortcode_1]
    

    But the parser does not like shortcode values as attributes in other shortcodes.

    It sounds like you're reliant on a few plugins and their shortcodes, so I don't suggest editing those shortcodes - but if you look at the Shortcode API it's pretty easy to add you own. For simplicity's sake, this example won't contain the "proper" methods of making sure the shortcodes exist/plugins are installed etc, and will just assume they are.

    // Register a new shortcode called [calendar_with_latlng]
    add_shortcode( 'calendar_with_latlng', 'calendar_with_latlng_function' );
    
    // Create the function that handles that shortcode
    function calendar_with_latlng_function( $atts ){
        // Handle default values and extract them to variables
        extract( shortcode_atts( array(
            'near_distance' => 20
        ), $atts, 'calendar_with_latlng' ) );
    
        // Get the current latlng from the gmw shortcode
        $gmw_current_latlng = do_shortcode( '[gmw_current_latlng]' );
    
        // Drop that value into the fullcalendar shortcode, and add the default (or passed) distance as well.
        return do_shortcode( '[fullcalendar near='. $gmw_current_latlng .' near_distance='. $near_distance .']' );
    }
    

    Provided [gmw_current_latlng] returns a useable format for your [fullcalendar] shortcode, you should now be able to use your new shortcode that combines the two: [calendar_with_latlng] or you can also add the near_distance attribute: [calendar_with_latlng near_distance=44].

    You would just need to put the above functions into your functions.php, create a Simple Plugin, or save them to a file and add it in your Must-Use Plugins directory.

提交回复
热议问题