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
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.
And use
isset
forif
statement. So PHP code must changed like this:First of all, give a name attribute to your submit button:
Then in your shortcode, check if the name is available in the
$_POST
array:Note that for shortcodes, you must
return
the output, notecho
it.Please put shortcode only to the page instead of HTML code and place following code to functions.php