問題描述

WordPress 有很好的過濾器支持,可以獲得各種特定的內容,並在輸出之前對其進行修改。像”the_content” 過濾器,它允許您在輸出到屏幕之前訪問一個帖子的標記。

我試圖找到一個 catch-all 過濾器,給我最後一個破解,在輸出之前修改完整的標記。有人知道嗎

我已經瀏覽過濾器列表了很多次,但沒有任何東西跳出來:http://adambrown.info/p/wp_hooks/hook/filters

(我已經點了一些 Wordpress-specific 社區的這個問題,但沒有收到一個答覆,以為我會轉向着名的 SO 。)

最佳解決辦法

AFAIK,沒有鈎子,因為主題使用 HTML 不會被 WordPress 處理。

但是,您可以使用 use output buffering 來捕獲最終的 HTML:

<?php
// example from php.net
function callback($buffer) {
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html><body>
<p>It's like comparing apples to oranges.</p>
</body></html>
<?php ob_end_flush(); ?>
/* output:
   <html><body>
   <p>It's like comparing oranges to oranges.</p>
   </body></html>
*/

次佳解決辦法

WordPress 沒有”final output” 過濾器,但您可以一起入侵。以下示例位於為項目創建的“Must Use” 插件中。

注意:我沒有使用任何可能使用”shutdown” 操作的插件進行測試。

該插件通過遍歷所有打開的緩衝區級別,關閉它們並捕獲其輸出。然後它觸發”final_output” 過濾器,回應過濾的內容。

可悲的是,WordPress 幾乎完全相同的過程 (關閉打開的緩衝區),但實際上並不捕獲緩衝區進行過濾 (只是刷新它),所以其他”shutdown” 操作將無法訪問它。因此,WordPress 的以上動作是優先的。

wp-content /mu-plugins /buffer.php

<?php

/**
 * Output Buffering
 *
 * Buffers the entire WP process, capturing the final output for manipulation.
 */

ob_start();

add_action('shutdown', function() {
    $final = '';

    // We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting
    // that buffer's output into the final output.
    $levels = ob_get_level();

    for ($i = 0; $i < $levels; $i++)
    {
        $final .= ob_get_clean();
    }

    // Apply any filters to the final output
    echo apply_filters('final_output', $final);
}, 0);

掛接到 final_output 過濾器的示例:

<?php

add_filter('final_output', function($output) {
    return str_replace('foo', 'bar', $output);
});

第三種解決辦法

問題可能是老了,但是我找到了一個更好的方式來做到這一點。

function callback($buffer) {
  // modify buffer here, and then return the updated code
  return $buffer;
}

function buffer_start() { ob_start("callback"); }

function buffer_end() { ob_end_flush(); }

add_action('wp_head', 'buffer_start');
add_action('wp_footer', 'buffer_end');

説明此插件代碼註冊兩個操作 – buffer_startbuffer_end

buffer_start 在 html 的頭部分的末尾執行。在輸出緩衝結束時調用參數 callback 函數。這發生在頁面的頁腳,當第二個註冊的操作 (buffer_end) 執行時。

callback 函數是您添加代碼以更改輸出值 ($buffer 變量) 的位置。然後,您只需返回修改後的代碼,頁面就會顯示。

注意確保為 buffer_startbuffer_endcallback 使用獨特的功能名稱,因此它們不會與您可能在插件中使用的其他功能衝突。

第四種辦法

@jacer,如果你使用下面的鈎子,header.php 也被包含。

function callback($buffer) {
    $buffer = str_replace('replacing','width',$buffer);
    return $buffer;
}

function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }

add_action('after_setup_theme', 'buffer_start');
add_action('shutdown', 'buffer_end');

第五種辦法

您可以嘗試查看 wp-includes /formatting.php 文件。例如,wpautop 函數。如果您正在尋找在整個頁面上做某事,請查看超級緩存插件。這將最終的網頁寫入緩存的文件。看看 plug-in 如何工作可能會給你一些想法。

參考文獻

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