Wordpress缓存SQL查询

There are a lot of sql queries in my wordpress theme, for example, 20 sql query in last 6 added posts. So, normally there are minimum 100-150 query in my website and my website is loading late because of this.

I heard about transient_api and tried to cache queries with it but I failed.

Here is my last added posts code:

<?php
    $gostermeid = $gosterme;
    $kategoriid = $kategori;
    $catquery = new WP_Query( 'cat=:-'.$gostermeid.'&posts_per_page='.$kactane.'&post_type[]=post&post_type[]=galeri&post_type[]=video&blazersix_update_post_thumbnail_cache=true' );
    while($catquery->have_posts()) : $catquery->the_post();
            ?>
                <div class="post">
.
.
.

And I tried caching them like this

<?php
                $gostermeid = $gosterme;
             $kategoriid = $kategori;
             if ( false === ( $catquery = get_transient( 'lastaddedcache' ) ) ) 

$catquery = new WP_Query( 'cat=:-'.$gostermeid.'&posts_per_page='.$kactane.'&post_type[]=post&post_type[]=galeri&post_type[]=video&blazersix_update_post_thumbnail_cache=true' );
while($catquery->have_posts()) : $catquery->the_post();
set_transient( 'lastaddedcache', $catquery, 12 * HOUR_IN_SECONDS );


            ?>

After this code, on the second refresh of my page, my last added posts are not showing. What am I doing wrong? How can I fix my code?

Thanks for help!

Your code ignores changes to the value of $catquery for twelve hours after you set it. That's what caching means. Your last added posts will not show.

You probably need to invalidate the cache when you add posts. That means you need to use delete_transient() from somewhere in the code path that adds new posts.

Adding a cache to an existing data system can be difficult, because you must either tolerate stale data or find every place the cache needs to be invalidated. Caching is a foundational concept in computer engineering, partly because it's hard.

Why not make use of W3 super cache or similar, and set it up to cache the database queries and objects? It will also help you by minifying assets, and caching the full site and its html.