Ordenar entradas por nombre de categoría y título

21 nov 2013, 18:27:57
Vistas: 29.8K
Votos: 5

Estoy tratando de averiguar cómo puedo mostrar mis entradas ordenadas por título de categoría (a-z) y en segundo lugar, por el título de las entradas dentro de cada categoría:

CATEGORÍA A
- Una entrada que comienza con a
- Porque quiero aparecer en segundo lugar
- Como sea, muéstrame ya

CATEGORÍA B
- Otra entrada que comienza con a
- Bueno, no se me ocurre otro título con B
- Supongo que entiendes la idea

¿Cómo puedo lograr esto?

1
Comentarios

¿Llegaste a hacer un seguimiento de la respuesta? ¿Fue la solución? Si no fue así: ¿por qué?

kaiser kaiser
21 may 2014 14:25:18
Todas las respuestas a la pregunta 4
1

Para obtenerlos desglosados por categoría, necesitas recorrer la lista de categorías y luego hacer una consulta en cada categoría:

$categories = get_categories( array ('orderby' => 'name', 'order' => 'asc' ) );

foreach ($categories as $category) {

   echo "Categoría es: $category->name <br/>";

   $catPosts = new WP_Query( array ( 'category_name' => $category->slug, 'orderby' => 'title' ) ); 

   if ( $catPosts->have_posts() ) {

       while ( $catPosts->have_posts() ) {
          $catPosts->the_post();
          echo "<a href='the_permalink()'>the_title()</a>";
       }

       echo "<p><a href='category/$category->slug'>Más en esta categoría</a></p>";

   } //fin if
  

} //fin foreach

wp_reset_postdata();
23 may 2014 21:38:50
Comentarios

Para escalabilidad, no recomiendo usar múltiples instancias de WP_Query cuando no son necesarias. Usar un solo get_terms y un único WP_Query es todo lo que necesitas. Luego tendrás todos los elementos y podrás usar array_filter para determinar qué publicaciones pertenecen a cada categoría.

Eric Holmes Eric Holmes
23 may 2014 22:21:22
0

Creo que te refieres a AGRUPAR publicaciones por categoría/taxonomía NO ORDENAR.

Aquí hay un código para AGRUPAR por categoría/taxonomía

  1. $terms = get_terms( 'my_cat_name' );

Aquí, cat_name es el nombre de la taxonomía, cuando la registras así: por ejemplo:

register_taxonomy( 'my_cat_name', array( 'custom_post_name' ), $args )
  1. Úsalo en la Consulta por ejemplo:

    $args = array(
       'post_type'  => 'custom_post_name',
       'my_cat_name' => $term->slug,
       'posts_per_page' => $no_of_posts,
    );
    
  2. Código completo:

    $terms = get_terms( 'CUSTOM_TAXONOMY_SLUG' );
    
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    
        $output .= '<ul class="category-list">';
        foreach ( $terms as $term ) {
    
            $output .= '<li class="single-cat">';
            $output .= '    <h3>' . $term->name . '</h3>';  //  Nombre de la Taxonomía/Categoría
    
                $args = array(
                    'post_type'     => 'POST_TYPE_SLUG',
                    'CUSTOM_TAXONOMY_SLUG' => $term->slug,
                    'posts_per_page' => -1,
                );    
    
                $the_query = new WP_Query( $args );
    
                if ( $the_query->have_posts() ) {
                    $output .= '<ul class="cat-post-list">';
                    while ( $the_query->have_posts() ) {
                        $the_query->the_post();
                        $output .='     <li class="cat-single-post">';
                        $output .='         <h4><a href="'.get_the_permalink().'">' .get_the_title(). '</a></h4>';
                        $output .='     </li><!-- .cat-single-post -->';
                    }
                    $output .= '</ul><!-- .cat-post-list -->';
                } 
                wp_reset_postdata();
            $output .= '</li><!-- .single-cat-item -->';
        }
        $output .= '</ul><!-- .category-list -->';
    }
    
11 jul 2015 14:19:34
2

Ampliando el trabajo de Maheshwaghmare;

<? 
$terms = get_terms( 'CUSTOM_TAXONOMY' );
if ( ! empty( $terms ) ){ ?>

<div class="POST_TYPE_PLURAL">

<?  foreach ( $terms as $term ) {
//print_r($term) // DEBUG;
$term_slug = $term->slug;
$term_name = $term->name;
$term_description = $term->description;
?>

    <div class="POST_TYPE_CATEGORY <?=$term_slug; ?>">

      <h1 class="section-head"> <?=$term_name; ?> </h1>
      <p><?=$term_description; ?> </p>

       <?  
        $args = array(
          'post_type'     => 'CUSTOM_POST_TYPE',
          'tax_query' => array(
            array(
              'taxonomy' => 'CUSTOM_TAXONOMY',
              'field'    => 'slug',
              'terms'    => $term_slug,
            ),
          ),
           'posts_per_page' => -1,
         );    

         $the_query = new WP_Query( $args );

           if ( $the_query->have_posts() ) : ?>
              <? while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

               <div class="POST_TYPE_SINGLE">
                <h3> <? the_title(); ?> </h3>
                <? // MÁS CÓDIGO DE PLANTILLA ?>
               </div>

             <?  endwhile;
           endif;
           wp_reset_postdata(); ?>
     </div>
 <?  } // foreach
 } //if terms
 ?>
21 nov 2016 12:21:12
Comentarios

Me interesaría saber si es mejor práctica seguir creando instancias de wp_query o si sería mejor crear un array a partir de una y luego usar el array para rellenar.

Chris Pink Chris Pink
21 nov 2016 12:22:54

Sería mejor si puedes explicar el código que publicaste y qué has ampliado de la respuesta anterior.

bravokeyl bravokeyl
21 nov 2016 13:28:41
0
-1

Puedes usar el parámetro orderby para una nueva instancia de wp_query:

$query = new WP_Query( array ( 'orderby' => 'title', 'order' => 'DESC' ) );

Así que para cada categoría usa una instancia separada.

Más información aquí: http://codex.wordpress.org/Class_Reference/WP_Query

6 dic 2013 23:26:57