You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress中如何从URL向自定义短代码传递参数?

Pass URL Parameters to Your Custom WordPress Shortcode

Hey there! Let’s figure out how to pass URL parameters to your [Shortcode] for displaying Calameo documents. Here’s a straightforward, WordPress-friendly solution tailored to your plugin:

Step 1: Modify Your Shortcode Callback Function

First, update the function that powers your shortcode to check for URL parameters and use them if available.

Assuming your current shortcode registration looks like this:

add_shortcode('Shortcode', 'calameo_document_shortcode');

Update the callback function to pull the vendor parameter from the URL (with proper security handling):

function calameo_document_shortcode($atts) {
    // Set default attributes for the shortcode
    $atts = shortcode_atts(
        array(
            'vendor' => 'default_vendor' // Fallback if no vendor is specified
        ),
        $atts,
        'Shortcode'
    );

    // Check if a 'vendor' parameter exists in the URL
    $url_vendor = get_query_var('vendor');
    if (!empty($url_vendor)) {
        // Sanitize input to prevent security risks
        $atts['vendor'] = sanitize_text_field($url_vendor);
    }

    // Your existing logic to fetch and display the Calameo document goes here
    // Example: $document_html = fetch_calameo_document($atts['vendor']);
    
    return $document_html;
}

Step 2: Register the Custom Query Variable (Best Practice)

To ensure WordPress recognizes the vendor parameter in URLs (and avoid conflicts with other plugins), register the query variable in your plugin:

function register_calameo_query_vars() {
    global $wp;
    $wp->add_query_var('vendor');
}
add_action('init', 'register_calameo_query_vars');

This makes the URL parameter accessible via get_query_var() and aligns with WordPress’s routing standards.

Step 3: Test It Out

  • Visit a page with your shortcode (e.g., https://your-site.com/doc-page?vendor=vendor2) — the shortcode will automatically use vendor2 from the URL.
  • If no URL parameter exists, it falls back to the value set in the shortcode (e.g., [Shortcode vendor=vendor1]) or the default default_vendor.

Optional: Adjust Priority (Shortcode vs. URL)

If you want the shortcode’s manually specified vendor to take precedence over the URL parameter, tweak the logic:

// Only use the URL parameter if no vendor is set in the shortcode
if (empty($atts['vendor'])) {
    $url_vendor = get_query_var('vendor');
    if (!empty($url_vendor)) {
        $atts['vendor'] = sanitize_text_field($url_vendor);
    }
}

Critical Security Reminder

Always sanitize user-provided input (like URL parameters) with functions such as sanitize_text_field() to prevent XSS attacks and other vulnerabilities.

内容的提问来源于stack exchange,提问作者Jens Skov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:02:46