PHP简码产生意外结果

时间:2018-11-24 14:01:42

标签: php regex wordpress woocommerce shortcode

这是按照here的说明,尝试在WordPress插件的上下文中创建PHP短代码:

function echo_postage_cost($html, $item, $images) {
    global $product;
    $sku = get_post_meta( $item['post_id'], '_sku', true );

    if ($sku == "/(^SY-).+/"){
      $postage_cost = "\$25";
    } else {
      $postage_cost = "FREE" ;
    }

    $html = str_replace( '[[postage_cost]]', '$postage_cost', $html );

    return $html;
}

add_filter( 'wplister_process_template_html', 'echo_postage_cost', 10, 3 );

然后应该使用[[postage_cost]]来调用函数的输出。

但是,即使_sku的值为“ SY-DB9-03-MM”,并且我们期望的是“ $ 25”,输出也始终是“ FREE”。我在哪里弄错了?

2 个答案:

答案 0 :(得分:3)

请尝试使用此代码,

function echo_postage_cost($html, $item, $images) {
    global $product;
    $sku = get_post_meta( $post->ID, '_sku', true );

    if (preg_match('/(^SY-).+/', $sku)){
      $postage_cost = "\$25";
    } else {
      $postage_cost = "FREE" ;
    }

    $html = str_replace( '[[postage_cost]]', '$postage_cost', $html );

    return $html;
}

add_filter( 'wplister_process_template_html', 'echo_postage_cost', 10, 3 );

答案 1 :(得分:1)

此:

if ($sku == "/(^SY-).+/"){

应为:

if (preg_match("/(^SY-).+/", $sku)){

或更简单:

if (preg_match("/^SY-/", $sku)){
相关问题