【问题标题】:execute php Shortcode on button click在按钮单击时执行 php Shortcode
【发布时间】:2021-03-13 08:35:50
【问题描述】:

我正在尝试在单击按钮时执行 php 短代码,但它没有运行。

HTML按钮代码如下..

<html>
<body>
<p align="center">
<button onclick="executeShortCode()">Refresh Date</button>

<script> 
function executeShortCode() {
alert("<?php echo do_shortcode('[Test_ShortCode]');?>");
}
</script>
</body>
</html>

PhP 简码如下..

<?php 
add_shortcode( 'Test_ShortCode', 'refresh_time' );
function refresh_time( )
{
echo "Refresh Button Press @  " . date("Y/m/d H/i/s") . "<br>";
}
?>

【问题讨论】:

  • 在没有 HTTP 请求的情况下,您无法通过单击按钮执行 PHP 代码。尝试使用 jQuery GET/POST 方法。
  • 你能推荐一个示例代码吗?
  • @shekharsinghal 在要求为您编写代码之前,您是否进行过任何研究?在 Stack Overflow 上已经有 plenty of relevant resources 讨论这个话题。
  • @esqew :我已经尝试了所有可用的示例。我从过去 5-6 天开始尝试这个,但没有任何帮助。这就是为什么我正在寻找有人自己尝试过的示例代码。

标签: php html wordpress shortcode


【解决方案1】:

假设你有一个PHP函数

remote_function.php

<?php 
    
    function refresh_time( )
    {
        echo "Refresh Button Press @  " . date("Y/m/d H/i/s") . "<br>";
    }

    // call your function 
    refresh_time();
?>

现在在按钮点击时使用AJAXGET方法调用它,如下所示

<!DOCTYPE html>
<html>
<head>
    <title>Refesh date</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <button onclick="executeShortCode()">Refresh Date</button>
    <p id="date">Date here</p>
</body>

<script type="text/javascript">
    function executeShortCode()
    {
        $.ajax({
            url: 'remote_function.php',
            type: 'get',
            success:function(data){
              document.getElementById('date').innerHTML = data;
            },
            error: function(xhr, status, error) {
              console.log(error);
           },
        });
    }
</script>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多