2017-09-05 56 views
0

所以我有一些代碼來修改wordpress中的the_content()過濾器。WordPress的the_content()過濾器檢查圖像是否存在

add_filter('the_content', 'filter_the_content_in_the_main_loop'); 

function filter_the_content_in_the_main_loop($content) { 

// Check if we're inside the main loop in a single post page. 
if (is_single() && in_the_loop() && is_main_query()) { 
    $patterns = array("/.jpg/", "/.jpeg/", "/.png/"); 
    if (isset($_COOKIE['webpsupport'])) // generated through modernizr detect webp 
     $content = preg_replace($patterns, "_result.webp", $content); 
    return $content; 
} 

return $content; 
} 

現在這個工作和轉換圖像格式.WEBP,但如果.WEBP圖像不存在於服務器上,我需要退回到原來的格式。

在我,因爲我可以用不同的頁面模板文件下面使用下面的代碼來測試,如果WEBP版本有:

$image = get_the_post_thumbnail_url($postId); 
$ext = pathinfo($image, PATHINFO_EXTENSION); 
$thePostThumbPath = str_replace("http://localhost", "", $thePostThumbUrl); 
    if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $thePostThumbPath)) 
     $thePostThumbUrl = str_replace("_result.webp", "." . $ext, $thePostThumbUrl); 

任何想法如何,我可以以有效的方式做到這一點。

乾杯

回答

0

您可以在過濾器應用中檢查現有的.webp圖像嗎?

$patterns = array("/.jpg/", "/.jpeg/", "/.png/"); 
if (isset($_COOKIE['webpsupport']) && $webpExists) 
    $content = preg_replace($patterns, "_result.webp", $content); 

如果是,那麼你不需要恢復圖像路徑回來。