query_posts doesn't order by title
-
19-04-2021 - |
Question
It seems like stupid bug, but how can i order by title? It anyways orders by date! I'm using:
query_posts( array(
'post_type' => 'page',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC'
) );
I want to use this in function as SHORTCODE. What i'm trying to achieve is to create site map / index of all entries in alphabetic order. Also i'm using newest WP.
Solution
Thanks to Chip Bennett who told me that i'm doing wrong by using query_posts
inside content. So i used get_posts
and i got what i wanted, thanks!
Here is sample of how can you do it, if you got the same problem as me:
function some_name(){
global $post;
$tmp_post = $post;
$args = array( 'post_type'=>'page', 'numberposts' => -1, 'orderby'=> 'title', 'order' => 'ASC' );
$myposts = get_posts( $args );
if ( !empty($myposts) ) {
foreach( $myposts as $post ) : setup_postdata($post);
the_title();
echo '<br>';
endforeach;
}
$post = $tmp_post;
}
OTHER TIPS
Another post has this code inside a function, but for those looking to simply add alphabetized posts to a custom theme, for example, you can use the following...
<?php // Alphabetize posts from the *** category
global $post;
$temp_post = $post;
$args = array( 'category' => *categoryID*, 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC' );
$these_posts = get_posts( $args );
if( !empty($these_posts) ) {
foreach( $these_posts as $post ) : setup_postdata($post);
?>
<?php
/* HTML/PHP code goes here to display each post */
the_title("<h2>", "</h2>");
the_content("<div class='content'>", "</div>");
?>
<?php
endforeach; // End of The Loop.
}
$post = $temp_post;
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange