I am writing the following code, which I have updated since the original question so as to give the entire picture. I am a newbie, and the reason why I am not using the get_posts() function in combination with an add_filter() is simply because I couldn't get it to work so I simply went back to my comfort zone and wrote a select statement. Hopefully my novice-ness doesn't get me any downvotes :-)
$search_term = $request->get('search');
$terms = $wpdb->get_results(
$wpdb->prepare("
SELECT *
FROM {$wpdb->posts}
WHERE {$wpdb->posts}.post_type = 'rz_listing'
AND {$wpdb->posts}.post_status = 'publish'
AND {$wpdb->posts}.post_title LIKE '%%" . stripslashes( $wpdb->esc_like($search_term) ) . "%%'
LIMIT $limit
")
);
if( ! is_wp_error( $terms ) ) {
if( ! empty( $terms ) ) {
foreach( $terms as $term ) {
$rz_row = $term;
// grab the icon Luke
$placeicon = get_post_meta( $term->ID, 'rz_listing_type', true );
$icon = get_post_meta( $placeicon, 'rz_icon', true );
}
}
}
As you can see, I run the first query to get the meta_value that is used as the post_id for the subsequent query. This appears to be a very inefficient way to make two database calls, is there another way of doing it?
get_post_meta
call won't hit the database unless you pass it a post ID you haven't fetched yet. Also are you sure$term->ID
should go in there?get_term_meta
is for term ID ( and the same applies to term meta too, WP_Cache stores it in memory until the end of the request, so if you copy paste that 100x, you don't get 100 new queries )WP_Query
instead, then you would no longer have lots of small queries to the post meta table. You've also used$wpdb->prepare
incorrectly. Also what isrz_listing_type
? Is this a field from a field API plugin that stores a post ID?term
has a very specific meaning in WordPress so I'd advise against using that as a variable name for non-term data,$posts
would be a better name and less confusingrz_icon
once per post, so if you callget_post_meta( 1, 'rz_icon', true );
20 times then only 1 database query happens$wpdb->prepare
in accordance with the documentation and changed $term to $post :-)