問題描述

我正在尋找一個解決方案,我如何計數和顯示在 WordPress 網站的所有查詢。有誰知道,如果有一個很好的外掛?

否則,這將是一個解決方案來檢查控制檯上的查詢,因為我在控制檯上工作很多。

最佳解決方案

您可以將此塊程式碼貼上到當前活動的 WordPress 主題 functions.php 檔案中:

function wpse_footer_db_queries(){
    echo '<!-- '.get_num_queries().' queries in '.timer_stop(0).' seconds. -->'.PHP_EOL;
}
add_action('wp_footer', 'wpse_footer_db_queries');

上面的程式碼塊將在主題的頁尾中呈現 HTML 註釋 (在</body></html> 之前,包含資料庫查詢的數量以及它們如何檢索日誌。

次佳解決方案

新增…

define( 'SAVEQUERIES', TRUE );

… 到 wp-config.php,並檢查 $wpdb->queriesshutdown 。這是最新的鉤子,唯一的一個,之後沒有查詢被觸發。此外,它也適用於 wp-admin/

示例程式碼作為外掛:

<?php
/**
 * Plugin Name: T5 Inspect Queries
 * Description: Adds a list of all queries at the end of each file.
 *
 * Add the following to your wp-config.php:

define( 'WP_DEBUG',         TRUE );
define( 'SAVEQUERIES',      TRUE );

 */

add_action( 'shutdown', 't5_inspect_queries' );

/**
 * Print a list of all database queries.
 *
 * @wp-hook shutdown
 * @return  void
 */
function t5_inspect_queries()
{
    global $wpdb;

    $list = '';

    if ( ! empty( $wpdb->queries ) )
    {
        $queries = array ();
        foreach ( $wpdb->queries as $query )
        {
            $queries[] = sprintf(
                '<li><pre>%1$s</pre>Time: %2$s sec<pre>%3$s</pre></li>',
                nl2br( esc_html( $query[0] ) ),
                number_format( sprintf('%0.1f', $query[1] * 1000), 1, '.', ',' ),
                esc_html( implode( "n", explode(', ', $query[2] ) ) )
            );
        }

        $list = '<ol>' . implode( '', $queries ) . '</ol>';
    }

    printf(
        '<style>pre{white-space:pre-wrap !important}</style>
        <div class="%1$s"><p><b>%2$s Queries</b></p>%3$s</div>',
        __FUNCTION__,
        $wpdb->num_queries,
        $list
    );
}

Update

在想了一會兒之後,我已經寫了一個更適合我需要的外掛 – 如果你喜歡這個控制檯,可能是你的外掛。

<?php
/**
 * Plugin Name: T5 Log Queries
 * Description: Writes all queries to '/query-log.sql'.
 * Plugin URI:  http://wordpress.stackexchange.com/a/70853/73
 * Version:     2012.11.04
 * Author:      Thomas Scholz
 * Author URI:  http://toscho.de
 * Licence:     MIT
 */

add_filter( 'query', 't5_log_queries' );

/**
 * Write the SQL to a file.
 *
 * @wp-hook query
 * @param   string $query
 * @return  string Unchanged query
 */
function t5_log_queries( $query )
{
    static $first = TRUE;
    // Change the path here.
    $log_path = apply_filters(
        't5_log_queries_path',
        ABSPATH . 'query-log.sql'
    );
    $header = '';

    if ( $first )
    {
        $time    = date( 'Y-m-d H:i:s' );
        $request = $_SERVER['REQUEST_URI'];
        $header  = "nn# -- Request URI: $request, Time: $time ------------n";
        $first   = FALSE;
    }

    file_put_contents( $log_path, "$headern$query", FILE_APPEND | LOCK_EX );

    return $query;
}

使用 tail(可用 on Windows if Git is installed) 跟蹤檔案:

$ tail -f query-log.sql -n 50

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。