Wordpress the_content() filter check if image exists

1k views Asked by At

So I have some code to modify the_content() filter in wordpress.

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;
}

now this works and converts the images to .webp format, but if the .webp image doesn't exist on the server I need to fall back to the original format.

In my template files for various pages I can use the following to test if the webp version is there using the following code:

$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);

Any ideas how I may do this in a efficient manner.

Cheers

1

There are 1 answers

0
Slava On

Can you check existing .webp image in filter applying ?

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

If yes then you don't need to revert image path back.