• Hi I have this code in a plugin which I am converting into a widget.
    It list all my posts in order of the event date. However it lists all my posts, what I want to do is just show 5 posts?

    Any idea on the below of where I would add ‘posts per page; or something?

    Thanks very much in advance

    function emw_events_list($atts, $content=NULL) {
    	global $wpdb;
    	$today = date('Y-m-d', strtotime('now'));
    	$events = $wpdb->get_results("SELECT posts.id, posts.post_title, meta.meta_value FROM {$wpdb->prefix}postmeta as meta INNER JOIN {$wpdb->prefix}posts as posts ON (meta.post_id = posts.id) WHERE (meta.meta_key = 'event_date' AND meta.meta_value >= '{$today}' AND posts.post_status='publish' and posts.post_date < NOW()) ORDER BY meta.meta_value");
    	if(is_array($events)) {
    		$output = "\t<ul class=\"events_list\">\n";
    		foreach ($events as $event) {
    			$event_link = get_permalink($event->id);
    			$event_date = date(get_option('date_format'), strtotime($event->meta_value));
    			$output .= "\t\t<li><a href=\"{$event_link}\">{$event->post_title}</a> ({$event_date})</li>\n";
    		}
    		$output .= "\t</ul>\n";
    	}
    	return $output;
    }
Viewing 4 replies - 1 through 4 (of 4 total)
  • I’m not great at php. But you should be able to add a counter to the foreach statement that breaks when you’ve reached 5. You can try this:

    $i=0;
                    $output = "\t<ul class=\"events_list\">\n";
    		foreach ($events as $event) {
                            if($i==5) break;
    			$event_link = get_permalink($event->id);
    			$event_date = date(get_option('date_format'), strtotime($event->meta_value));
    			$output .= "\t\t<li><a href=\"{$event_link}\">{$event->post_title}</a> ({$event_date})</li>\n";
                            $i++;
    		}

    Moderator bcworkz

    (@bcworkz)

    Counting output will work, but if you have many posts, adding LIMIT 5 to your query will be way more efficient. When you start getting into pagination or complex restrictions, creating a new WP_Query object would be easier for most people to work with instead of elaborate mySQL queries.

    Thread Starter rob_870

    (@rob_870)

    LIMIT 5 works very well – thanks so much .

    If I wanted to show particular category would it be CATEGORY ‘x’ ?

    Moderator bcworkz

    (@bcworkz)

    It’s almost that easy if you created a WP_Query object, but using $wpdb methods you need to join in the various terms tables, as categories are just another taxonomy. Exactly how one does that in mySQL gives me a headache, so I can’t be much help with that approach.

    If you want to try out WP_Query, review Class_Reference/WP_Query#Category_Parameters, you’ll see it’s much more straight forward unless you’re already a wiz at complex mySQL queries.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Restrict number of posts in a plugin’ is closed to new replies.