2

I am trying to execute a php shortcode on button click but that is not running.

HTML button code is as follow..

<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 shortcode is as follow..

<?php 
add_shortcode( 'Test_ShortCode', 'refresh_time' );
function refresh_time( )
{
echo "Refresh Button Press @  " . date("Y/m/d H/i/s") . "<br>";
}
?>
4
  • 2
    You can not execute PHP code with a button click without an HTTP request. Try using the jQuery GET/POST method. Commented Dec 1, 2020 at 12:24
  • can you suggest a sample code for that. Commented Dec 4, 2020 at 9:35
  • @shekharsinghal Have you researched anything before asking for code to be written for you? There are plenty of relevant resources on this very topic already on Stack Overflow. Commented Dec 4, 2020 at 13:16
  • @esqew : I have tried most off all the available examples. I am trying this since last 5-6 days but nothing helped. that's why i am looking for the example code that someone have tried himself. Commented Dec 5, 2020 at 5:26

1 Answer 1

1

Suppose you have a PHP function in

remote_function.php

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

    // call your function 
    refresh_time();
?>

Now call it using the AJAX GET method on button click as follows

<!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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.