skip to Main Content

I have a problem with WordPress shortcode and Elementor. Let’s say that I have the following shortcode inside functions.php:

function some_shortcode($atts) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        echo 'It works!';
    }
}

add_shortcode('shortcode', 'some_shortcode');

Next, i put the following HTML code to page using Elementor:

[shortcode]
<form method="POST">
    <button type="submit">Click me</button>
</form>

I’d really love to the shortcode function executes only when the user clicks the form button (so when the POST method happens) but in fact, the shortcode is executed all the time (looks like if the condition inside the shortcode function doesn’t work). Could you tell me, please, how can I make the shortcode working only after the form button click?

3

Answers


  1. You must enter a field of the form to be submitted within your condition. For example, the name button of the submission button or the name of the input field.

    [shortcode]
    <form method="POST">
        <button type="submit" name="my-form-submitted">Click me</button>
    </form>
    

    And use isset for if statement. So PHP code must changed like this:

    function some_shortcode($atts) {
        if ( isset( $_POST['my-form-submitted'] ) ) {
            echo 'It works!';
        }
    }
    
    add_shortcode('shortcode', 'some_shortcode');
    
    Login or Signup to reply.
  2. First of all, give a name attribute to your submit button:

    <form method="POST">
        <button type="submit" name="trigger_shortcode">Click me</button>
    </form>
    

    Then in your shortcode, check if the name is available in the $_POST array:

    function some_shortcode($atts) {
        if (isset($_POST['trigger_shortcode'])) {
            return 'It works!';
        }
    }
    add_shortcode('shortcode', 'some_shortcode');
    

    Note that for shortcodes, you must return the output, not echo it.

    Login or Signup to reply.
  3. Please put shortcode only to the page instead of HTML code and place following code to functions.php

    function some_shortcode($atts) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            return 'It works!';
        }
        echo '<form method="POST"><button type="submit">Click me</button></form>';
    }
    
    add_shortcode('shortcode', 'some_shortcode');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search