Need to optimize this PHP script for "recent posts". Fatal error when post count is high...

Posted by Scott B on Stack Overflow See other posts from Stack Overflow or by Scott B
Published on 2010-03-23T19:53:05Z Indexed on 2010/03/23 20:23 UTC
Read the original article Hit count: 349

Filed under:
|

The code below is resulting in an error on a site in which there are ~ 1500 posts. It performs fine when post count is nominal, however, this heavy load is exposing the weakness of the code and I'd like to optimize it.

Interestingly, when I disable this menu and instead use the "Recent Posts" widget, the posts are drawn fine. So I'd probably do good to borrow from that code if I knew where to find it, or better yet, If I could call the widget directly in my theme, passing it a post count variable.

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 16384 bytes) in /home1/est/public_html/mysite/wp-includes/post.php on line 3462

The code is below. Its purpose is to list "recent posts".

global $post; 
$cat=get_cat_ID('myMenu'); 
$cathidePost=get_cat_ID('hidePost'); 
$myrecentposts = get_posts(array('post_not_in' => get_option('sticky_posts'), 'cat' => "-$cat,-$cathidePost",'showposts' => $count-of-posts));
$myrecentposts2 = get_posts(array('post_not_in' => get_option('sticky_posts'), 'cat' => "-$cat,-$cathidePost",'showposts' => -1));
$myrecentpostscount = count($myrecentposts2);

if ($myrecentpostscount > 0) 
{ ?>
    <div class="recentPosts"><h4><?php if ($myHeading !=="") { echo $myHeading; } else { echo "Recent Posts";} ?></h4><ul>
    <?php 
    $current_page_recent = get_post( $current_page );
    foreach($myrecentposts as  $idxrecent=>$post) {
        if($post->ID == $current_page_recent->ID)
            {
                $home_menu_recent = ' class="current_page_item';
            } 
            else 
            {
                $home_menu_recent = ' class="page_item';
            }
            $myclassrecent = ($idxrecent == count($myrecentposts) - 1 ? $home_menu_recent.' last"' : $home_menu_recent.'"'); 
        ?>
    <li<?php echo $myclassrecent ?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php } ; if (($myrecentpostscount > $count-of-posts) && $count-of-posts > -1){ ?><li><a href="<?php bloginfo('url'); ?>/recent">View All Posts</a></li><?php } ?></ul></div>

© Stack Overflow or respective owner

Related posts about php

Related posts about Wordpress