【问题标题】:Does get_post_meta() makes a separate query to the database?get_post_meta() 是否对数据库进行单独查询?
【发布时间】:2020-05-08 03:10:29
【问题描述】:

我很久以前就不得不问的一个问题。我很好奇这些 wordpress 函数(如 get_post_meta)是对数据库进行 sql 查询,还是在加载页面时将其加载到 WP_Query 全局变量中?谢谢

【问题讨论】:

    标签: mysql sql wordpress


    【解决方案1】:

    get_post_meta() 是 get_metadata() 的包装器,get_metadata() 使用全局 WP_Object_Cache 对象。

    相关代码为:

    function get_metadata( $meta_type, $object_id, $meta_key = '', $single = false ) {
       ...
        $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
    
        if ( ! $meta_cache ) {
            $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
            if ( isset( $meta_cache[ $object_id ] ) ) {
                $meta_cache = $meta_cache[ $object_id ];
            } else {
                $meta_cache = null;
            }
        }
        ...
    }
    

    如果数据不在缓存中,wp_cache_get() 正在检查全局 WP_Object_Cache 对象 $wp_object_cache 和 update_meta_cache() 正在更新全局 WP_Object_Cache 对象 $wp_object_cache。当然,此更新需要 SQL 查询。

    顺便说一句,全局 WP_Object_Cache 对象 $wp_object_cache 不仅仅用于发布元数据 - 它是一个通用缓存,WordPress 和插件使用它来缓存重新计算代价高昂的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多