Home › Forums › Front-end Issues › Query posts based on radio button field › Reply To: Query posts based on radio button field
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:
<?php
$field = get_field_object("field_5039a99716d1d");
?>
<form action="<?php echo home_url('slug/to/archive'); ?>" method="get">
<ul>
<?php foreach( $field['choices'] as $k => $v ): ?>
<li>
<label><input type="radio" name="acf_category" value="<?php echo $k; ?>" /><?php echo $v; ?></label>
</li>
<?php endforeach; ?>
</ul>
<input type="submit" value="Go" />
</form>
<?php
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
Thanks
E
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.