WordPress的the_content()过滤器检查图像是否存在

问题描述:

所以我有一些代码来修改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); 

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

干杯

您可以在过滤器应用中检查现有的.webp图像吗?

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

如果是,那么你不需要恢复图像路径回来。