【问题标题】:Using PHP variables in Wordpress Shortcodes在 Wordpress 简码中使用 PHP 变量
【发布时间】:2013-07-02 13:52:15
【问题描述】:

我正在使用 Cart66 Wordpress 插件,我正在尝试在短代码中包含一个变量,您可以看到以下代码:

$price = do_shortcode('[add_to_cart item="test-item" showprice="only" text=""]').' test';
echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="'.$price.'" ]');

我做了一些谷歌搜索,显然这是在 Wordpress 短代码中包含变量的正确方法,但这似乎对我不起作用,Cart66 只是退回并使用默认的“添加到购物车”文本代替上面短代码中定义的文本。

谁能看出我哪里出错了?

【问题讨论】:

    标签: php wordpress shortcode


    【解决方案1】:

    正如您使用谷歌搜索在简码中添加文本是正确的,但并不完全正确。

    您使用了“do_shortcode()”函数,该函数用于替换简码功能并在前端显示其功能。但是,如果您想在短代码中添加参数并使其正常工作,则需要稍微更改短代码功能。

    您必须在包含简码功能的文件中找到简码:

    找到类似下面的代码:
    add_shortcode('add_to_cart','function_name');
    function function_name($atts)
    {
    $atts //-- will be used to add parameters as you needed
    }

    【讨论】:

      【解决方案2】:

      你可以使用PHP的Output Buffering control

      PS:do_shortcode() 本身不会回显输出;绑定在该操作上的任何内容也可能会自行回显,即当您 (A) 编辑插件或 (B) 使用 OB 时。

      【讨论】:

        【解决方案3】:

        我认为返回值中有一些奇怪的字符导致了问题,我使用了下面的表达式代码,它似乎解决了我的问题:

        $value = substr(do_shortcode('[add_to_cart item="test-item" showprice="only" text=""]'), 0, 4).' Test';
        $patterns = array();
        $patterns[0] = '/"/';
        $replacements = array();
        $replacements[2] = ' ';
        $value = preg_replace($patterns, $replacements, html_entity_decode($price, ENT_QUOTES));
        echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="'.$price.'" ]');
        

        不用说这是一个非常...复杂的解决方案。我最终通过使用 Wordpresses WPDB class 使用了一些好的旧 SQL。将大约 7 行代码变成 2 行:

        $priceValue = $wpdb->get_var("SELECT price FROM wp_cart66_products WHERE id = x");
        echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="£'.$priceValue.' Membership" ]');
        

        这是一个更好的解决方案,我不建议尝试将短代码用于它们不打算用于的事情。

        【讨论】:

          【解决方案4】:

          ‘add_shortcode’ 函数不允许您使用外部变量。它在本地范围内运行,因此任何声明为 INSIDE 的变量都将被识别,但任何变量 OUTSIDE 都不会被识别。如果要使用外部变量,则需要使用 global。

          在您的外部变量上使用 global 会将其拉到范围内,并允许您在 add_shortcode 函数中使用它! :)

          $greeting = "hello world!";   //external variable
          
          function run_greeting() {
            global $greeting         //pulls variable within scope
            echo $greeting;
          }
          add_shortcode( 'greeting_shortcode', 'run_greeting' );

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-04-07
            • 1970-01-01
            • 2023-03-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-08-27
            相关资源
            最近更新 更多