Wordpress: get_posts() function problem

Discussion in 'PHP' started by GSto, Sep 25, 2008.

  1. #1
    I am trying to write an add-on to my wordpress blog that show the most recent post in each category. whenever I try to use the get_posts() method, it always returns the most recent post, regardless of what argument I use. even if I tell it to get 5 posts, it just returns the first post 5 times! here is a snippet of the code I am using:

    function the_category_box(){
    
         $catIDs = get_all_category_ids(); 
         $control = 0;  //total number posted so far
         $columns = 3; //number of columns in table
         
         echo "<table>";
         foreach($catIDs as $cat){
    	         $catName = get_catname($cat); //getting cagegory name
    	         $args = array(
    	                 'numberposts' => 1
                             'category' => $cat
    	                 );
    	         $catPosts = get_posts($args); //<-- THE PROBLEM
    	         if($control%$columns == 0){   echo "<tr>";   } 
    	         echo "<td> <h4> Latest in <b>$catName</b></h4>";
    	             foreach($catPosts as $post){
    		             setup_postdata($post);
    			         the_title();
    			         echo "<a href=\"";
    			         the_permalink();
    			         echo"\">Read More--></a>";
    	             }
    	         echo"</td>";
    	         if($control%$columns == 2){   echo "</tr>";   }
    	         $control++;
              }     
         }
         echo "</table></div>";   
         return;
    }
    
    PHP:
    Is there a better way to do this, or how can I get this function to work?
     
    GSto, Sep 25, 2008 IP
  2. Warden

    Warden Peon

    Messages:
    22
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I usually don't like using other developer's functions, especially when I don't understand them or when they don't work properly. That's why I would recommend you just query the database directly, without using Wordpress' native functions. It does require some PHP and MySQL knowledge, but the results are just the way you want.

    I'm not familiar with Wordpress' backend so I'm not sure how to guide you further, but basically you need to see how the database looks like and then query 5 rows for each category id, ordering the results descending by date.
     
    Warden, Sep 25, 2008 IP
  3. javaongsan

    javaongsan Well-Known Member

    Messages:
    1,054
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    128
    #3
    <?php query_posts("cat=$cat&showposts=1");?>
    Code (markup):
     
    javaongsan, Sep 25, 2008 IP