如何显示Wordpress的所有数据库查询?

时间:2010-03-18 20:17:02

标签: database wordpress

使用类似于described here的方法,我可以看到加载页面时在Wordpress中进行的查询总数。

现在,我想显示页面加载时正在进行的所有数据库查询。这样我就可以看到我最大的资源是谁,而无需完成我所有插件和主题脚本的删除过程。

显示Wordpress所做的所有数据库查询的最佳方式是什么?

4 个答案:

答案 0 :(得分:40)

如果您将define('SAVEQUERIES', true)添加到配置文件中,则可以通过在主题中添加以下内容来列出为当前页面所做的所有查询。

if (current_user_can('administrator')){
    global $wpdb;
    echo "<pre>";
    print_r($wpdb->queries);
    echo "</pre>";
}

有关详细信息,请参阅文档:http://codex.wordpress.org/Editing_wp-config.php#Save_queries_for_analysis

答案 1 :(得分:5)

或者你可以挂钩到posts_request。您可以将coe设置在functions.php中,例如

add_filter('posts_request','debug_post_request'); // debugging sql query of a post

function debug_post_request($sql_text) {

   $GLOBALS['debugku'] = $sql_text; //intercept and store the sql<br/>
   return $sql_text; 

}

在主题页脚中,您可以使用print_r,如

print_r($GLOBALS['debugku']);

答案 2 :(得分:1)

使用Query Monitor

这是一个免费的开源插件,您可以在其中过滤各种上下文中的查询,例如:

  • 哪个插件叫
  • 花费最多时间的查询
  • 重复查询
  • 您可以通过选择/更新/插入/删除进行过滤

还有其他事情...

how to see what queries wordpress is running

答案 3 :(得分:1)

我想在页面底部添加查询/经过时间,在此处添加代码:

/**
 * show all sql at footer if it defined in wp-config.php:
 * define('SAVEQUERIES', true);
 */
function plg_name_show_debug_queries()
{
    if (defined('SAVEQUERIES') && SAVEQUERIES) {
        global $wpdb;
        if (is_array($wpdb->queries)) foreach ($wpdb->queries as $key => $q) {
            list($query, $elapsed, $debug) = $q;
            $time = number_format(($elapsed * 1000), 3);
            $count = $key + 1;
            $total_time += $elapsed;
            echo "
            <div style=\"position: relative; z-index: 9999    ; background: black; color: white; padding:10px\">
                $count - Query: $query <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Time: $time ms
            </div>";
        }
        echo "
        <div style=\"position: relative; z-index: 9999    ; background: black; color: white; padding:10px\">
            Total Queries: " . count($wpdb->queries) . "<br>Total Time: " . number_format(($total_time * 1000), 3) . " ms
        </div>";
    }
}
add_action('admin_footer', 'plg_name_show_debug_queries', PHP_INT_MAX);
add_action('wp_footer', 'plg_name_show_debug_queries', PHP_INT_MAX);