Home Forums Front-end Issues Query posts based on radio button field Reply To: Query posts based on radio button field

  • Hi @bounty_digital

    I don’t think your code is following the correct logic path for this to work.
    Your code needs to be spit up into 2 parts:

    1. Create the radio button where a user can select the category and then be redirected to the archive url with the $_GET param

    2. hook into the pre_get_posts filter and look for the $_GET param. If it exists, add the meta query in.

    I should really write a tutorial for this one, so I’m happy to write the code. This is the most simple way to get it working:

    $field = get_field_object("field_5039a99716d1d");
    <form action="<?php echo home_url('slug/to/archive'); ?>" method="get">
    	<?php foreach( $field['choices'] as $k => $v ): ?>
    			<label><input type="radio" name="acf_category" value="<?php echo $k; ?>" /><?php echo $v; ?></label>
    	<?php endforeach; ?>
    	<input type="submit" value="Go" />
    add_filter( 'pre_get_posts', 'my_pre_get_posts' );
    function my_pre_get_posts( $query ) {
    	if( isset($_GET['my_custom_category']) )
    		// $query is the WP_Query object, set is simply a method of the WP_Query class that sets a query var parameter
    		$query->set( 'meta_key', 'acf_field_name' );
    		$query->set( 'meta_value', $_GET['acf_category'] );
    	return $query;

    This code has not been tested, you can see the 2 parts of code. The rest will be up to you to test it and fix any issues it contains!

    Good luck