【问题标题】:using if/else statement with str_replace to add variables via shortcode使用带有 str_replace 的 if/else 语句通过简码添加变量
【发布时间】:2016-08-26 06:46:13
【问题描述】:

我正在使用一个自定义简码,它生成一个自定义贝宝按钮并将特定参数传递给贝宝结帐表单。

我正在使用 str_replace 函数将短代码中定义的属性传递给 html 表单。

如果未在短代码中定义为属性,我想设置默认样式类和默认标题。

我的 php:

function paypal_button_func($attrs){


$class=$attrs['class']; //Added button style class variable 
$title=$attrs['title']; //Added button title variable 



if( isset( $atts['title'])) //add button title to the form html
{
return $html=str_replace('[title]',$title,$html); 
} 

//This sets the default title if not defined
else {
    return $html=str_replace ('[title]','SIGN UP NOW',$html); 
}

这是我的html

<input type="submit" class="[class]" value="[title]" /> <!-- updated class and value for addtl shortcode parameters -->

我成功地使用以下代码将短代码属性传递给 html,但问题是如果属性未在短代码中定义,它会将 [class] 和 [title] 输出为值,即不是我想要发生的。

$html=str_replace('[title]',$title,$html); //add button title assigned to the form    
$html=str_replace('[class]',$class,$html); //replaces class assigned to the form

【问题讨论】:

    标签: php html shortcode


    【解决方案1】:

    只需确保正确初始化替换,我建议在创建变量时使用 if/else 简写:

    $class = isset($attrs['class']) ? $attrs['class'] : 'default-class-name'; //Added button style class variable 
    $title = isset($attrs['title']) ? $attrs['title'] : 'SIGN UP NOW'; //Added button title variable 
    

    这样,您的 html 将始终得到替换,无论是 attrs 值还是默认值。

    我还注意到您在isset($atts['title']) 上检查了一个错字,您可能想要$attrs 而不是$atts

    祝你好运!

    【讨论】:

    • 那个短手完美地工作了。在过去这么多小时盯着我的屏幕,那个错字就从我身边溜走了。感谢您的帮助!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2015-11-09
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多