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

时间:2017-09-05 06:21:19

标签: wordpress hook fallback webp

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

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

干杯

1 个答案:

答案 0 :(得分:0)

您可以在过滤器申请中查看现有的.webp图片吗?

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

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

相关问题