Search code examples
phpwordpress

WordPress adding get_posts results and re-ordering


I am doing a series of loops which uses:

$myposts = get_posts("category=$category->id");

Which gets all posts for the given category. However I need to do something like:

$myposts .= get_posts("category=$category->id"); 

so the var $myposts is added to on each loop. I then need to re-order $myposts by published date and re-loop.

Any idea how I can achieve this?

My complete code is:

global $wpdb;
$categories = $wpdb->get_results("SELECT $wpdb->terms.term_id AS id, name, description 

from $wpdb->terms INNER JOIN $wpdb->term_taxonomy ON $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id WHERE parent = '2' ORDER BY name ASC");
echo '<ul class="results">';
foreach($categories as $category) :
?>
<?php global $post;
$myposts = get_posts("category=$category->id");
foreach($myposts as $post) : setup_postdata($post);
?>
<li>
<a class="title" href="<?php the_permalink(); ?>"><span><?php the_title(); ?></span><br/><?php echo $category->name; ?></a>
<a class="image" href="<?php the_permalink(); ?>"><?php echo get_the_post_thumbnail($post->ID, 'result') ?></a>
</li>
<?php endforeach; ?> 

<?php endforeach; 
echo '</ul>';

Thanks,

Dave


Solution

  • at the simplest level, you cannot concatenate (use the dot operator as you would on strings) on arrays. try using array_merge

    $myposts = get_posts("category=$category->id");
    $myposts = array_merge($myposts, get_posts("category=$category->id"));
    

    Although, I think what you are trying to achieve is a listing of posts from several categories correct? The above example will give possible duplicates (if same post is in multiple categories) try the more WP way of doing this:

    //array of categories
    $categories = array();
    
    // I assume you are looping through something to get the multiple `$category->id`
    for($some_category_objs as $category)
    {
        $categories[] = $category->id;
    }
    
    // query for posts where the post has every category in the list
    $myposts = query_posts(array('category__and' => $categories));
    
    // query for posts where the post matches any of the categories
    $myposts = query_posts('cat='.implode(",", $categories));
    

    Your post was a little vague on what your goal was.. let me know if i'm off base. Also, check out: http://codex.wordpress.org/Template_Tags/query_posts

    EDIT

    $args = array(
        'category__in' => $categories, // $categories is an array of all the categories to search in
        'orderby' => 'date', // ORDER  BY DATE
        'order' => 'DESC', // NEWWST FIRST
    );
    $my_posts = get_posts($args);