First, you don’t need a raw SQL query, and by using one you give up all of WP’s optimisations.
For example, if you run the query twice, it runs twice. If you had used WP_Query
to getch those posts though, it would save them the first time to avoid making additional queries. It’s even possible those posts are present as a result of other queries.
On top of that, caching plugins have limited options for working with your query, and you have to do all the validating/sanitising yourself.
So do something like this:
$q = new WP_Query( [
'post_type' => 'acf-field',
'posts_per_page' => 50,
] );
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
// ...
}
wp_reset_postdata();
}
Second, you don’t need to faff around renaming columns and fetching individual fields. You’re doing additional heavy lifting, and making it difficult to draw from already fetched data, and avoiding WP APIs.
Since your field_name
is just the post excerpt, and your field_label
is the post title, just use get_the_excerpt()
and get_the_title()
inside the loop.
The final result will naturally avoid duplicate queries, as WP will store what it fetched in WP_Cache
and use it the second time around. If you install an object cache drop in with Redis/MemcacheD/etc, it’ll avoid the query entirely.
A general rule of thumb in WP, is that if you need to do a raw SQL query to fetch data from anything other than a custom table, either something has gone terribly wrong, or you’re making an incredibly expensive query that needs to go in a CLI command or a cron job.