Misma taxonomía para varios tipos de post: ¿cómo ocultar vacíos en un tipo de post específico?

26 ago 2016, 23:27:41
Vistas: 3.2K
Votos: 6

Tengo una taxonomía "artist" para dos tipos de post personalizados diferentes ("project" y "product").

Necesito mostrar una lista de "artists", pero solo si tienen "products" relacionados, y solo si esos productos están aún en stock.

$artists = get_terms( array(
   'taxonomy' => 'artist',
   'hide_empty' => 1,
) );

Esto incluye artistas que tienen "projects" pero no "products". ¿Es posible especificar para qué tipo de post debe referirse el argumento "hide_empty"?

EDIT Esto es lo que tengo hasta ahora.

        /*
        Útil cuando una taxonomía aplica a múltiples tipos de post
        fuente: http://wordpress.stackexchange.com/a/24074/82
    */
    function get_terms_by_post_type( $taxonomies, $post_types ) {

        global $wpdb;

        $query = $wpdb->prepare(
            "SELECT t.*, COUNT(*) from $wpdb->terms AS t
            INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
            INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id
            INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
            WHERE p.post_type IN('%s') AND tt.taxonomy IN('%s')
            GROUP BY t.term_id",
            join( "', '", $post_types ),
            join( "', '", $taxonomies )
        );

        $results = $wpdb->get_results( $query );
        return $results;
       }

$artists = get_terms_by_post_type( array('artist'), array('product'));

//*
if( !empty($artists) && !is_wp_error( $artists )  ){

    // filtrar artistas con productos sin stock
    foreach($artists as $k=>$artist){
        $args = array(
            'post_type'     => 'product',
            'post_status'   => 'publish',
            'posts_per_page' => -1,
            'tax_query' => array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'artist',
                    'field' => 'id',
                    'terms' => array( $artist->term_id )
                ),
                array(
                    'key' => '_stock_status',
                    'value' => 'instock'
                )
            )
        );
        $query = new WP_Query($args);
        echo $artist->slug;
        pr($query->post_count);

        if($query->post_count<1){
            unset($artists[$k]);
        }
    }
}

Casi funciona, pero no elimina los productos que están sin stock.

1
Comentarios

Creo que necesitarás una función personalizada. Esta respuesta podría ayudarte: http://wordpress.stackexchange.com/a/14334/32698

Nate Allen Nate Allen
27 ago 2016 00:06:55
Todas las respuestas a la pregunta 2
0

Otra solución al mismo problema que es un poco más corta y menos compleja:

function get_terms_by_posttype($taxonomy, $postType) {
    // Obtener todos los términos que tienen posts
    $terms = get_terms($taxonomy, [
        'hide_empty' => true,
    ]);

    // Eliminar términos que no tienen ningún post en el tipo de post actual
    $terms = array_filter($terms, function ($term) use ($postType, $taxonomy) {
        $posts = get_posts([
            'fields' => 'ids',
            'numberposts' => 1,
            'post_type' => $postType,
            'tax_query' => [[
                'taxonomy' => $taxonomy,
                'terms' => $term,
            ]],
        ]);

        return (count($posts) > 0);
    });

    // Devolver lo que nos queda
    return $terms;
}
1 jul 2021 10:43:54
0

Gracias a esta respuesta, pude ver la luz. Aquí te muestro cómo consultar términos de taxonomía relacionados con productos (de WooCommerce) que están "en stock". Utiliza tanto tax_query (para relacionar producto con taxonomía) como meta_query (para filtrar productos sin stock).

$artists = get_terms_by_post_type( array('artist'), array('product'));

if( !empty($artists) && !is_wp_error( $artists )  ){

    // filtrar artistas de productos sin stock
    foreach($artists as $k=>$artist){
        $args = array(
            'post_type'     => 'product',
            'post_status'   => 'publish',
            'posts_per_page' => -1,
            'meta_query' =>array(
                'relation' => 'AND',
                array(
                    'key' => '_stock_status',
                    'value' => 'instock',
                    'compare' => '='
                )
                ,
                array(
                    'key' => '_stock',
                    'value' => '0',
                    'compare' => '>'
                )
                ,
                array(
                    'key' => '_stock',
                    'value' => '',
                    'compare' => '!='
                )
            ),
            'tax_query' => array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'artist',
                    'field' => 'id',
                    'terms' => array( $artist->term_id )
                ),


            )
        );

        $query = new WP_Query($args);

        if($query->post_count<1){
            unset($artists[$k]);
        }
    }
}

function get_terms_by_post_type( $taxonomies, $post_types ) {

    global $wpdb;

    $query = $wpdb->prepare(
        "SELECT t.*, COUNT(*) from $wpdb->terms AS t
        INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
        INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id
        INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
        WHERE p.post_type IN('%s') AND tt.taxonomy IN('%s')
        GROUP BY t.term_id",
        join( "', '", $post_types ),
        join( "', '", $taxonomies )
    );

    $results = $wpdb->get_results( $query );

    return $results;

}
27 ago 2016 02:49:21