0

I have a plugin that will sorts posts on the search page and taxonomy page. The loop has already taken care of narrowing down the results, so what i need is to be able to sort the post my a custom meta value. In this case price. I want to be able to reach into the existing query, replace any special characters, then sort based on the clean meta value.

I used this select, but the problem is it querys all posts on the database instead of the reults found in wp_query and this can slow down the sort tremendously

function join_it( $join ) {
global $wpdb;
    $sym = get_option('sort_by_ignore');
    $join .= "LEFT JOIN (SELECT $wpdb->prefix" . "postmeta.post_id AS ID, CAST(REPLACE(REPLACE(REPLACE($wpdb->prefix" . "postmeta.meta_value, ',', ''), '" . $sym . "',''),' ','') AS SIGNED) AS price FROM $wpdb->prefix" . "postmeta WHERE meta_key = 'my_price'" . ") P ON (P.ID = wp_posts.ID)";

return $join;
}
add_filter('posts_join', 'join_it' );

$args = array_merge( $wp_query->query, array('caller_get_posts' => 1,'paged' => $paged ));

        query_posts($args);
thesanerone
  • 87
  • 1
  • 10

1 Answers1

1

If you're only using it for sorting, you may be better off using the posts_orderby filter, rather than posts_join.

If you're finding the filter's affecting other queries, you could use remove_filter once it's run where you need it.

My answer here does something vaguely similar (without cleaning the values with the replace function - you'd have to leave that in, I think).

Community
  • 1
  • 1
Hobo
  • 7,536
  • 5
  • 40
  • 50