Wp查询缓存

时间:2012-09-19 02:24:42

标签: mysql wordpress

我在这里有一点问题..让我介绍......

我有一个脚本来创建一个短代码..这是脚本..

//shortcode stock
function stok($atts, $content = null) {  
    extract(shortcode_atts(array(  
        "id" => 'http://net.tutsplus.com'  
    ), $atts));  
    $result = mysql_query("SELECT SUM(quantity) AS value_sum FROM wp_wpsc_cart_contents WHERE prodid = '".$id."'"); 
    $row = mysql_fetch_assoc($result); 
    $stock = '<center><br><b>STOK TERJUAL :</b><div class="nscountdown"><table><thead><tr><td>'.$row['value_sum'].'</td></tr></thead></table></div></center>';
    return $stock;
}  
add_shortcode("stok", "stok");  

正如您所看到的那样,存在一个对列进行求和的查询

$result = mysql_query("SELECT SUM(quantity) AS value_sum FROM wp_wpsc_cart_contents WHERE prodid = '".$id."'"); 

Nah ..问题是..如何缓存结果,因为该查询使我的服务器负载平均变得尖峰......

任何解决方案??

之前感谢....

1 个答案:

答案 0 :(得分:0)

您可能需要Transient API

function stok($atts, $content = null) {  
    extract(shortcode_atts(array(  
        "id" => 'http://net.tutsplus.com'  
    ), $atts));  

    if ( false === ( $query_cache = get_transient( md5($id) ) ) ) {
        $result = mysql_query("SELECT SUM(quantity) AS value_sum FROM wp_wpsc_cart_contents WHERE prodid = '".$id."'"); 
        $row = mysql_fetch_assoc($result); 
        $stock = '<center><br><b>STOK TERJUAL :</b><div class="nscountdown"><table><thead><tr><td>'.$row['value_sum'].'</td></tr></thead></table></div></center>';

        // set one hour lifetime cache with the name of md5($id)
        set_transient( md5($id), $stock, 60*60*1 );     
        return $stock;
    }
    return $query_cache;
}  
add_shortcode("stok", "stok");