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

WordPress自定义短代码问题:动态追踪号码属性切换失效

Fixing Your WordPress Dynamic Tracking Phone Shortcode

Hey there! Let's work through the two issues in your shortcode code right away:

1. Why tracking="homepage" Isn't Working

The core problem here is that you’re using a single equals sign (=) in your conditional checks instead of a comparison operator (== or ===).

A single = is for assigning values, not checking if two values are equal. So when you write if ($args['tracking'] = 'general'), you’re actually forcing $args['tracking'] to be 'general' every time the code runs—this condition will always evaluate to true, no matter what the original tracking attribute was set to. That’s why even with tracking="homepage", you still get the general number.

2. Cleaning Up Redundant $out Code

Your two $out lines are nearly identical, with only the tracking number changing. We can simplify this by first fetching the correct tracking number, then building the anchor tag just once instead of repeating the same HTML structure twice.

Corrected Code

Here’s the revised function that fixes both issues:

// Dynamic tracking number shortcode
function dynamic_tracking_phone_number( $atts , $content = null ) {
    // Set default attribute value
    $args = shortcode_atts( array( 
        'tracking' => '', 
    ), $atts);
    
    // Store tracking numbers in an array for easy lookup
    $tracking_numbers = array(
        'general' => '4255209',
        'homepage' => '6015036'
    );

    // Validate tracking attribute exists and is valid
    if ( empty( $args['tracking'] ) || !isset( $tracking_numbers[$args['tracking']] ) ) {
        return 'Please specify a valid tracking attribute (general or homepage)';
    }

    // Get the matching tracking number
    $selected_number = $tracking_numbers[$args['tracking']];
    
    // Build the output once (no redundant code!)
    $out = '<a href="tel:+1561' . $selected_number . '" target="_blank">' . $content . '</a>';

    return html_entity_decode($out);
}
add_shortcode( 'phone', 'dynamic_tracking_phone_number' );

Key Improvements

  • Fixed the tracking attribute bug: Used array lookup to directly fetch the correct number based on the tracking value, avoiding the equality check mistake entirely.
  • Removed redundancy: The anchor tag is built only once, with the dynamic number plugged in—no more duplicate HTML code.
  • Better validation: Now checks if the provided tracking value is actually one of the supported options, returning a clearer error message if not.

Testing this with [phone tracking="homepage"]561-444-4440[/phone] will now output the correct homepage tracking number in the tel: link.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:54:53