Ordinare wp_query per titolo

7 ott 2011, 20:51:46
Visualizzazioni: 23K
Voti: 3

Ho dei titoli di post che iniziano con un prezzo, ad esempio: $199,900 - 123 Street. Sto usando il codice seguente, ma non riesco a far funzionare correttamente l'ordinamento ascendente per titolo. Qualche suggerimento per favore.

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
 'cat' =>21,
 'posts_per_page' => 999999,
 'paged' => $paged,
 'orderby' => 'title',
 'order' => 'ASC',
 );
$the_query = new WP_Query($args);
?>
<div id="listings">

<?php if ($the_query->have_posts()) : ?>

<?php while ($the_query->have_posts()): $the_query->the_post(); ?>
        <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
            <div class="title1 active_listing">
                <?php
                if (in_category('6')) {
                the_title();
                } else {
                ?>

                <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>
                <?php
                }
                ?>
            </div>

                <div class="alignleft thumb"><?php the_post_thumbnail('thumbnail'); ?>
<br />
</div>
        <div class="content"><?php the_excerpt(); ?> </div>

                <?php
                if (in_category('6')) {
                ?>
<br />
                <?php
                } else {
                ?>
 <a href="<?php the_permalink() ?>" rel="bookmark">Visualizza Dettagli</a>
 <br />
                <?php
                }
                ?>

        </div>

    <?php endwhile; wp_reset_postdata();?>

<?php else : ?>

    <h2 class="center">Non Trovato</h2>
    <p class="center">Spiacenti, ma stai cercando qualcosa che non è presente qui.</p>
    <?php get_search_form(); ?>

<?php endif; ?>

</div>
0
Tutte le risposte alla domanda 1
2

Se stai cercando di farli ordinare per prezzo crescente, il problema è che l'ordinamento per titolo è un confronto tra stringhe, non numerico. Una soluzione sarebbe quella di inserire il prezzo in un campo personalizzato e ordinare in base al tuo campo personalizzato anziché al titolo. Dovresti aggiungere un parametro meta_key con il nome della tua chiave meta, e ordinare per meta_value_num. Consulta WP_Query nel Codex per maggiori informazioni.

Inoltre, se vuoi che tutti i post vengano restituiti (cosa che presumo sia quello che stai cercando di fare impostando un numero così alto), puoi impostare posts_per_page a -1 e rimuoverà la clausola LIMIT dalla query.

7 ott 2011 22:29:41
Commenti

Grazie mille Milo! Funziona perfettamente! Avevo visto l'uso di meta_key e meta_value durante la mia ricerca per una soluzione, ma non ho mai capito completamente il loro funzionamento e il collegamento con i campi personalizzati.

spiderling spiderling
7 ott 2011 23:26:55

Nel 2023 usiamo 'orderby' => 'title_num',

Tim Hallman Tim Hallman
9 feb 2023 01:35:13