I am trying to search a custom post type via title using a form and query variables, what I am struggling with is getting the results to update properly. Currently, when the page loads it shows all results as expected, but when I input something into the search field and search, it shows all the results instead of the expected one, the url does update with the query var as well.
archive-researcher.php
<section>
<form id="researcher" method="GET" action="<?php echo get_post_type_archive_link('researcher'); ?>">
<div>
<input type="text" name="r_name" placeholder="Search">
</div>
<div>
<button>Search</button>
<a href="<?php echo get_post_type_archive_link('researcher'); ?>">Reset</a>
</div>
</form>
<div class="row">
<?php if (have_posts()): ?>
<?php while (have_posts()): the_post(); ?>
<div class="col-12 col-lg-4 d-flex">
<?php get_template_part('template/card', 'researcher'); ?>
</div>
<?php endwhile; ?>
<?php else: ?>
<div class="col-12">
<p>No researchers found.</p>
</div>
<?php endif; ?>
</div>
<?php the_posts_pagination(); ?>
</section>
</main>
</div>
<?php get_footer(); ?>
functions.php
function researcher_archive($query)
{
// only run this query if we're on the researcher archive page and not on the admin side
if (
$query->is_archive("researcher") &&
$query->is_main_query() &&
!is_admin()
) {
// get query vars from url.
// https://codex.wordpress.org/Function_Reference/get_query_var#Examples
$r_name = get_query_var("r_name", false);
$query->set("s", $r_name);
$query->set('posts_per_page', 12);
$query->set('orderby', 'wpse_last_word');
$query->set('order', 'ASC');
}
}
add_action("pre_get_posts", "researcher_archive");