• Resolved Tom Combs

    (@tcwebguru)


    I’m creating a plugin that will only be used in the wordpress admin, not on the front site of the site.

    I’ve created a custom post type called “sports_players”
    I’ve also created several custom taxonomies that are only used with that custom post type, for example: “player_age”, “player_sport”, “player_sport_level”
    There’s also a metabox that holds the “player_id”.

    What I want to do is get a list of all of the sports listed in “player_sport” (example: football, baseball, basketball, etc) and put them in a dropdown box. Which I have been able to do in several ways, but this is the code I’m using at the moment for that

    <div class="wrap">
         <h2><?php _e( 'Select A Sport' ); ?></h2>
              <form id="ar-sport-form" action="" method="POST">
    <div>
         <?php
         $args = array(
         'show_option_none' => __( 'Select A Sport' ),
         'show_count'       => 0,
         'orderby'          => 'name',
         'echo'             => 0,
         'taxonomy'        => 'sports_roster_category',
         );
         ?>
    
    <?php $select  = wp_dropdown_categories( $args ); ?>
    <?php $replace = "<select$1 onchange='return this.form.submit()'>"; ?>
    <?php $select  = preg_replace( '#<select([^>]*)>#', $replace, $select ); ?>
    <?php echo $select; ?>
    <noscript>
    <input type="submit" name="ar-roster-submit" value="<?php _e('Get Results', 'athletic-roster'); ?>"/>
    </noscript>
    </div>
    </form>
    </div><!-- .wrap -->

    When someone selects one of the sports from the drop down, using AJAX I want to display a table that shows all of the posts from the sports_player custom post type, along with all of the custom taxonomies and meta data associated with that post entry.

    What I need help with at the moment is trying to figure out how to get all of the data from the posts associated with the selected custom post taxonomy.

    Also, I need to accomplish this without installing any additional plugins.

    Any help would be greatly appreciated.
    Thanks

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    If you’re using AJAX initiated onchange, you don’t really need the submit button. If you want to use one anyway, your JS needs a .click() handler to initiate the AJAX.

    How to setup AJAX in the WP environment is covered starting here and runs on for several pages:
    https://developer.www.ads-software.com/plugins/javascript/

    You’ll want to initiate the AJAX server request using the POST method. Then the selected sport will be in $_POST in your PHP AJAX callback, keyed under the dropdown field’s assigned name attribute.

    You may query for the appropriate posts using WP_Query class as usual. When you loop through the results, output your table HTML like you would for a web page. Just realize this data is collected by the AJAX jQuery function into a single variable, it does not automatically appear on screen.

    That single variable is passed to the jQuery response handler. Here you can set the response as the inner HTML of a container that was initially output for this purpose.

    None of this probably makes much sense unless you’ve become familiar with doing AJAX within WP according to the linked article. The whole AJAX process can be challenging to setup at first. Once you have the basic framework working, altering it to do more complex tasks becomes easier.

    Debugging AJAX PHP callbacks can be difficult. I like to setup a page template as a testbed that calls the AJAX callback directly without using jQuery or admin-ajax.php. This allows us to fine tune the PHP code as we normally would outside of the AJAX process. Then when you call the function through AJAX you can be confident the output will be as expected.

    Thread Starter Tom Combs

    (@tcwebguru)

    bcworkz,
    Thanks for the direction and explanation.
    So I’ve spent the last 12hrs learning about how ajax works with wordpress and I’ve made some progress, but I’m still stuck trying to figure out what to do next.

    I checked the console log and I can see that the slug of my custom taxonomy is being passed to the javascript file. However, I’m not sure how I can pass that slug back to php as a variable so that I can use it to run a query to generate my output.

    This is what my code looks like that generates the dropdown

    $categories = get_terms(array('taxonomy' => 'sports_roster_category'));
      		  $select = "<select name='cat' id='cat' class='postform'>n";
      		  $select.= "<option value='-1'>Select category</option>n";
    
    		  foreach($categories as $category){
    			if($category->count > 0){
    				$select.= "<option value='".$category->slug."'>".$category->name."</option>";
    			}
    		  }
    
    		  $select.= "</select>";
    
    		  echo $select; { ?>
              <img src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" id="roster_loading" class="waiting" style="display:none;" />
    
         </div>
         <div id="roster_results"></div>
    		<?php	}

    This is my javascript code. By viewing the console log, I can see that when I select an option in the dropdown, that the selection is being passed to javascript

    jQuery(document).ready(function($) {
    	var sel = document.getElementById('cat');
    	var slug = sel;
    
    	$('#cat').change(function(){
    		 $('#roster_loading').show();
    		 data = {
    			 action: 'roster_get_results',
    			 roster_nonce: roster_vars.roster_nonce,
    
    		};
    		 $.post(ajaxurl, data, function(response) {
    		 	$('#roster_results').html(response);
    			$('#roster_loading').hide();
    	});
    		 console.log( slug.value );
    		 return false;
    	 });
    
    });

    What I can’t figure out how to do, is pass the “var slug” back to php as variable so that I can use it in my query to display the results based upon which dropdown category is selected.

    Moderator bcworkz

    (@bcworkz)

    Add your value to the data array

    data = {
       sport: slug.value,
       action: 'roster_get_results',
       ...

    In PHP get the value with $_POST['sport']

    Thread Starter Tom Combs

    (@tcwebguru)

    bcworkz…
    Very sorry for the delay in getting back.
    Thanks for your help on this issue.

    I was trying things similar to your suggestion, but i wasn’t adding the .value. Once I did that, everything worked perfectly.

    Thanks again!!

    Moderator bcworkz

    (@bcworkz)

    You’re most welcome. Those silly little details will get you every time ??

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Query Posts based upon options selected in a Category Dropdown’ is closed to new replies.