WordPress.org

Ready to get started?Download WordPress

Forums

posts_join and posts_fields filters on Custom Post Type - Minimize query penalty (1 post)

  1. Driftless
    Member
    Posted 1 year ago #

    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);
    }

Topic Closed

This topic has been closed to new replies.

About this Topic