php – how to pass parameters to wordpress shortcode?

As docs for the add_shortcode() condition,

Each shortcode callback is passed by default three parameters, an array of attributes ($atts), shortcode content or null if not set ($content), and finally the shortcode tag itself ($shortcode_tags), in that order. is included.

Use shortcode_atts() To define which attributes are allowed and set default values ​​for those attributes.

function my_wpdiscuz_shortcode( $_atts ) {
    $defaults = array(
        'post_id' => '',
    );
    $atts = shortcode_atts( $defaults, $_atts );
    // Confirm that $post_id is an integer.
    $atts['post_id'] = absint( $atts['post_id'] );
    // ----
    // Now you can use $atts['post_id'] - it will contain
    // the integer value of the post_id set in the shortcode, or
    // 0 if nothing is set in the shortcode.
    // ----
    $html = "";
    if (file_exists(ABSPATH . "wp-content/plugins/wpdiscuz/themes/default/comment-form.php")) {
        ob_start();
        include_once ABSPATH . "wp-content/plugins/wpdiscuz/themes/default/comment-form.php";
        $html = ob_get_clean();
    }
    return $html;
}
add_shortcode("wpdiscuz_comments", "my_wpdiscuz_shortcode");

Note, if post_id Your shortcode is not set in the call, it will by default 0,

Leave a Comment