1

I have seen articles on how to add parameters to shortcodes, so that I can say something like [my-shortcode post_id=7], to pass a post ID to a shortcode.

Let's say I have a form on my page and the user enters something or selects something and based on that I want to refresh the content represented by the shortcode using user-supplied parameter(s).

How is this accomplished?

4

Let's say you have a form that sends the data in the following way:

<form method="post" name="car-select" action="<?php echo site_url('/my-page/'); ?>">
    <select name="make">
        <option value="benz">Benz</option>
        <option value="bmw">BMW</option>
        <option value="audi">Audi</option>
    </select>
    <input type="submit" value="Find my dream car!"/>
</form>

Now you want to query some posts based on users choice right? This is where $_POST comes in handy:

add_shortcode('my-shortcode','my_shortcode_function');
function my_shortcode_function($atts){
    // Get the ID from shortcode
    $id = $atts['post_id'];
    // Check if the form data has been sent
    if (isset($_POST['make']) && $id){
        $car_manufacturer = $_POST['make'];
        //Now, you have the form's data. Do whatever you want with it
        return $my_shortcode_values;
    }
}

You have to extend this code to fit your needs, such as defining what to do if there is no form data.

| improve this answer | |
  • I can see that this answers my question, but I don't have to pass a parameter to the shortcode, the function just has to get the POST data and do something with it. – Russell Eubanks Jun 13 '17 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.