Save a database query and update it automatically every X hours. WordPress

i’m a beginner and i need some help to optimize my “All Posts” page.

I have a page with all my published posts (300+). I display them whit this code:

Read More
while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 
    <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>">
    <?php the_title();?></a>
        <?php 
            global $wpdb;
            $postid = $post->ID;
            $postTit = $wpdb->get_var( "SELECT posttitle FROM wp_posts WHERE ID=" . $postid);
            echo "{$postTit}";
        ?>
    <div class="comments">
        <?php 
            global $wpdb;
            $postid = $post->ID;
            $commCount = $wpdb->get_var( "SELECT comment_count FROM wp2_posts WHERE ID=" . $postid);
            echo "{$commCount }";
        ?>
    </div>
<?php endwhile;

The question is:

I was thinking to “store” the query and update it hourly. I tried to Google something about it without success. I’ll appreciate if someone can tell me at least what i need to search since i’m a beginner in these kind of things.

(Sorry for bad English)

Edit 1

You guys think its a good idea to convert Data from MySQL to JSON using PHP and update it every hour ?

Related posts

1 comment

  1. You can use wp_cron() function for automatic save and updating purpose:

    if ( ! wp_next_scheduled( 'my_task_hook' ) ) {
      wp_schedule_event( time(), 'hourly', 'my_task_hook' );
    }
    
    add_action( 'my_task_hook', 'my_task_function' );
    function my_task_function() {
      wp_mail( 'your@email.com', 'Automatic email', 'Automatic scheduled email from WordPress.');
    }
    

    You will need to adapt it to your needs.

Comments are closed.