我想在 HTML 中动态显示服务价格。我在 MySQL 数据库中有价格。我创建了短代码来单独获取每个服务的价格,所以如果我有 10 个服务(我多次显示其中一些服务),我需要进行许多 SQL 查询。我怎样才能让它更快并减少数据库的负载?
这是我的简码
function get_service_price($atts) {
$a = shortcode_atts(array(
'service_name' => '',
'location_id' => '',
'vehicle_id' => ''
), $atts);
$service_name = $a['service_name'];
$location_id = $a['location_id'];
$vehicle_id = $a['vehicle_id'];
global $wpdb;
$result = $wpdb->get_row($wpdb->prepare(
"SELECT price FROM {$wpdb->prefix}services WHERE service_id = %s AND location_id = %s AND vehicle_id = %s",
$service_name,$location_id,$vehicle_id
));
return esc_html($result->price)."€";
}
您可以做的一件事是使用 wp_cache_set() 和 wp_cache_get() 将数据缓存固定时间(例如一分钟),这反过来会减少运行自定义查询的次数页面加载,从而同时提高性能。
例如:
function get_service_price($atts) {
$a = shortcode_atts(array(
'service_name' => '',
'location_id' => '',
'vehicle_id' => ''
), $atts);
/** Generate an unique key for this request */
$cache_key = 'service_price_' . md5( json_encode($a) );
/**
* Check whether we have cached data for this request.
*
* @see https://developer.wordpress.org/reference/functions/wp_cache_get/
*/
$price = wp_cache_get( $cache_key );
if ( false === $price ) {
$service_name = $a['service_name'];
$location_id = $a['location_id'];
$vehicle_id = $a['vehicle_id'];
global $wpdb;
$result = $wpdb->get_row($wpdb->prepare(
"SELECT price FROM {$wpdb->prefix}services WHERE service_id = %s AND location_id = %s AND vehicle_id = %s",
$service_name,$location_id,$vehicle_id
));
$price = $result->price;
/**
* Store this data in cache.
*
* @see https://developer.wordpress.org/reference/functions/wp_cache_set/
* @see https://codex.wordpress.org/Easier_Expression_of_Time_Constants
*/
wp_cache_set( $cache_key, $price, '', MINUTE_IN_SECONDS ); // Store in cache for one minute
}
return esc_html($price)."€";
}
这只是一个 POC,还有改进的空间,但至少应该让您很好地了解可以采取哪些措施来提高短代码的性能。