Support

Account

Home Forums Front-end Issues Using Checkbox values as query

Unread

Using Checkbox values as query

  • Hello,

    For a page on which I’m displaying a table with courses I’d like a sidebar which should be used as a filter for the table.

    I’m using the checkbox ‘trainingscategory’. I’d like to show all available values in the sidebar with a link. Once link is clicked it will show all posts in teh table containing that have that value.

    I’m sure I’m not the first one to do this, however I can’t find or don’t understand the way to approach this.

    My guess is that the best way would be to use a query. So I went to make a my_pre_get_posts in functions for my post type ‘training’.

    <?php
    function my_pre_get_posts( $query ) {
    	// do not modify queries in the admin
    	if( is_admin() ) {	
    		return $query;
    	}
    	
    	// only modify queries for 'training' post type
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'training' ) {
    		// allow the url to alter the query
    		if( isset($_GET['trainingscategory']) ) {
        		$query->set('meta_key', 'trainingscategory');
    			$query->set('meta_value', $_GET['trainingscategory']);
        	} 
    	}
    	// return
    	return $query;
    }
    add_action('pre_get_posts', 'my_pre_get_posts');

    That’s about as far as I came. I have trouble understanding how to properly use the query and to load the values.

    To load the ‘trainingscategory’ in the sidebar I used the following:

    <?php
    
    // Load field settings and values.
    $field = get_field_object('trainingscategory');
    $cats = $field['value'];
    
    // Display labels.
    if( $cats ): ?>
    <ul>
        <?php foreach( $cats as $cat ): ?>
            <li><?php echo $field['choices'][ $cat ]; ?></li>
        <?php endforeach; ?>
    </ul>
    <?php endif; ?>

    It doesn’t show the values since none are set for the page I suppose but I can’t figure out how to show them and use them to set a query for the table.

    Lastly I’d like to show the posts which have the selected cats. But I’m unsure how to make the query to show these results. I’ve read the documentation and forums about order by custom fields, query posts and url parameters a dozen times but I can’t string it together for some reason. I’m sure it’s obvious and I’ve been oblivious but the pieces just won’t fall for me. If someone could guide me in the right direction I would appreciate that alot.

    Kind regards,

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.