WordPress.org

Support

Support » Plugins and Hacks » Hacks » posts_join and posts_fields filters on Custom Post Type – Minimize query penalty

posts_join and posts_fields filters on Custom Post Type – Minimize query penalty

  • Finding woefully little information posts_join and posts_fields filters on WP_Query. I’ve implemented as below, and am wondering:

    1. Is this more efficient (MySQL / memory use) than ‘get post, do separate wpdb query to get the joined table and fields’
    2. Does this properly set the filter to fire only when a wp_query call includes post_type ‘fact’
    3. Is there a way to set it to filter ONLY on post_type fact (not for all posts included in a WP_Query that might include posts, pages, facts, etc — which won’t have data on the join (or does this matter MySQL-wise?)
    add_filter('posts_join', 'fact_join');
    function fact_join($join){
    	global $wp_query, $wpdb;
    
    	if (!empty($wp_query->query_vars['post_type']) && $wp_query->query_vars['post_type'] == 'fact') {
    		$fact_meta_table = $wpdb->prefix . "fact_meta";
    		$join .= "LEFT JOIN ". $fact_meta_table . " ON $wpdb->posts.ID = ". $fact_meta_table .".id ";
    	}
    	return ($join);
    }
    
    add_filter('posts_fields', 'fact_fields');
    function fact_fields($fields){
    	global $wp_query, $wpdb;
    
    	if (!empty($wp_query->query_vars['post_type']) && $wp_query->query_vars['post_type'] == 'fact') {
    		$fields .= ", " . $wpdb->prefix . "fact_meta.*";
    	}
    	return ($fields);
    }
  • The topic ‘posts_join and posts_fields filters on Custom Post Type – Minimize query penalty’ is closed to new replies.
Skip to toolbar