【问题标题】:How to convert this php code in a wordpress shortcode?如何将此 php 代码转换为 wordpress 短代码?
【发布时间】:2017-04-02 12:54:11
【问题描述】:

您好,我在网上找到了这个代码,它是一个简单的按钮,可以显示优惠券代码并同时打开 URL。

function coupon_add($coup, $uurl)
{
echo "    
<script type='text/javascript'>
<!--
function coupon(coup,url) 
{alert('COUPON CODE: ' + coup);
window.open(url,'_blank');
}
//-->
</script>";    
echo "<center><br /><input style=\"width:250px; height:60px;font-
size:30px;\" type=\"button\" onclick=\"coupon('".$coup."','".$uurl."')\" 
value=\"VIEW COUPON\" \/></center><p>";
}

我想把它变成一个短代码,以便我可以将它插入到帖子中。希望得到一些帮助,在此先感谢!

【问题讨论】:

    标签: php wordpress shortcode


    【解决方案1】:

    在你的functions.php中:

    add_shortcode( 'my_coupon_add', 'sc_my_coupon_add' );
    function sc_my_coupon_add( $args, $content = null ){
      $atts = shortcode_atts( array(
        'coup' => '',
        'uurl' => ''
      ), $args, 'my_coupon_add' );
      return "<script type='text/javascript'>
        function coupon( coup, url ){
          alert( 'COUPON CODE: ' + coup );
          window.open( url, '_blank' );
        }
       </script>  
       <center><br /><input style=\"width:250px; height:60px;font-size:30px;\" type=\"button\" onclick=\"coupon('" . $atts[ 'coup' ] . "','" . $atts[ 'uurl' ] . "')\" value=\"VIEW COUPON\" \/></center><p>";
    }
    

    现在您可以使用简码 [my_coupon_add coup="" uurl=""] 并传递您的参数。 javascript的编写方式,只能在页面或帖子上使用一次,否则coupon()函数会出现问题,但这应该足以让您在需要多次扩展/重写它(比如将 coupon() javascript 函数移动到一个主 js 文件,以便它只在需要时可用)。

    您可能需要仔细检查单引号和双引号 - 我很快就完成了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2019-11-19
      • 2019-05-26
      • 2018-06-24
      相关资源
      最近更新 更多