Return to Snippet

Revision: 34239
at October 19, 2010 20:11 by errkk


Initial Code
// Get custom taxonomies
// Get array of taxonomies eg activity, difficulty, subject
$taxonomies = get_taxonomies( array('_builtin' => false, 'public' => true),'objects' ); 
// foreach taxonomy, get a list of options to sort by, terms, eg maths, science
foreach ( $taxonomies as $tax => $tax_obj ){ 
    $terms[$tax_obj->query_var] = get_terms($tax_obj->name); // array of terms
}

// check stuff in GET is a registered taxonomy
$tax_args = array();
foreach ( $_GET as $key => $val ){
    if( array_key_exists($key, $terms) ){ 
        // if its set, add an argument for get_posts
        if( $val ){
            $tax_args[$key] = $val;
        }
    }
}
        


// build lines of conditions for if there are taxonomical requirements in the query string
$sort_conditions = '';
$required_matches = -1;

if( count( $tax_args ) ){
    $sort_conditions.= " WHERE 0=1 "; // add this so other stuff can just repeat ORs
    foreach( $tax_args as $key => $slug ){
        $sort_conditions.= " OR taxonomy = '$key' AND slug = '$slug' ";
        $required_matches ++;
    }
}

$sql ="
SELECT count(1) AS matches,t1.* FROM(

    SELECT wp_posts.*, wp_term_taxonomy.taxonomy, wp_terms.slug
        FROM wp_posts
            LEFT JOIN wp_term_relationships ON(wp_posts.ID = wp_term_relationships.object_id)
            LEFT JOIN wp_term_taxonomy ON(wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
            LEFT JOIN wp_terms ON(wp_term_taxonomy.term_id = wp_terms.term_id)
            JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
    WHERE wp_posts.post_type = 'post'
        AND (wp_posts.post_status = 'publish')
        AND wp_postmeta.meta_key = 'priority'
        AND wp_posts.post_status = 'publish'
    ORDER BY wp_postmeta.meta_value ASC, wp_posts.post_date DESC
    LIMIT 0, 999) AS t1

    $sort_conditions
GROUP BY ID HAVING matches > $required_matches";

$listing = $wpdb->get_results( $sql );

Initial URL


Initial Description


Initial Title
Custom Taxonomy post listing filter for WordPress with sort options

Initial Tags
sql, wordpress, filter

Initial Language
PHP