Support » Developing with WordPress » Change Shortcode ID based on dropdown list selection

  • I am trying to alter the ID of a shortcode value based on the selection of a dropdown list. The user selects a territory and the related uberchart should load.

    	function territory_shortcode()
    	{?>
        <form name="territory" id="territory" method="post" action="">
    	<select>
    
            <option value="" disabled selected>Choose Territory</option>
    		<option value="80">USA</option>
    		<option value="78">UK</option>
    		<option value="76">Brazil</option>
    		<option value="64">Australia</option>
       </select>
    </form>
    	<?php
    		if($_POST["territory"]){
    			$territory=$_POST["territory"];
    			echo do_shortcode( '[uberchart id="$territory"]' );
    		}
    		else{
    			echo do_shortcode( '[uberchart id="80"]' );
    		}
    }
    	add_shortcode( 'displaychart', 'territory_shortcode');

    Is what I have so far but it doesn’t work – do I need to use AJAX?
    Many thanks

    • This topic was modified 4 months, 2 weeks ago by bcworkz. Reason: code fixed
Viewing 1 replies (of 1 total)
  • There are several problems here.
    1. You put the name on your form element and expect that to be set. But forms can contain many inputs, each with their own name.
    2. You don’t handle the existing value, but always show the “Choose Territory” selection.
    3. There is no submit button, to submit the form.
    4. You are not sanitizing the input.
    5. You don’t need to call do_shortcode. You can call the actual handler directly, to avoid having to parse the shortcode.
    6. Shortcode handlers should never echo anything. They should return the value.

    It seems like you would only use this shortcode once on a page, but just to be complete, the variable being checked is not unique per shortcode, so it would only work once on a page.
    The use of AJAX is optional. It would require more code. It is only needed when you want to load the data without reloading the entire page.

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.