在将文件加载到网页之前检查文件是否存在

Checking if a file exist before loading it into webpage

我构建了一个 php 函数,它根据自定义字段中指定的内容更改 WordPress post 的背景,例如 red001(将加载 https://example.com/img/backgrounds/red001.jpg

花了很长时间,因为我不太擅长 php,但它需要改进,我需要帮助才能开始工作。

这是脚本,一旦插入 functions.php 将处理后台。

<?php
// Set background from custom field via "rbpet_background_image" function
function rbpet_post_background() {

    if ( $background = get_post_meta( get_the_ID(), 'usp-custom-background_image', true ) ) { 
$backgroundpre = "https://example.com/img/backgrounds/";
$backgroundpost = ".jpg";
$newbgurl = $backgroundpre . $background . $backgroundpost;
?>
        <style type="text/css">
            body { background-image: url( "<?php echo ($newbgurl); ?>")!important; }
        </style>
    <?php }
}
add_action( 'wp_head', 'rbpet_post_background' );

如我所写,它有效,但是,如果我现在想要一个 gif、png 或电影的背景?

我不想在自定义字段中指定,我该怎么做?

我在想办法检查 .jpg 文件是否存在然后加载它,如果不存在,请检查 .gif 文件是否存在然后加载它,如果不存在,请检查 .mp4 文件是否存在... . 这有可能吗?

这可能是一种方法。

function rbpet_post_background () {

    if ( empty( $background = get_post_meta( get_the_ID(), 'usp-custom-background_image', true ) ) ) return;
    $base = "https://example.com/img/backgrounds/";
    $extensions = array( ".jpg" , ".gif" , ".mp4" );

    foreach ( $extensions as $ext ) {

        $file = $base . $background . $ext;
        $file_headers = @get_headers( $file );
        if ( $file_headers[0] == "HTTP/1.1 200 OK" ) {
            $background_url = $file;
            break;
        }

    }

    if ( empty( $background_url ) ) return;

    wp_add_inline_style( "admin-checklist-handle" , 'body { background-image: url("' . $background_url . '")!important; }' );

}

add_action( "wp_head" , "rbpet_post_background" );

您可以使用 file_exists 而不是 get_headers。这在性能方面会更好。但是,您需要确定 $base 位于您的服务器上,并且您需要使用路径而不是 URL。

我花了几个小时才解决为什么它不起作用。

@Sebastian W 使用脚本完成了主要工作,我只是更改了它加载文件的方式

    // set background based on custom field in post
    function rbpet_post_background () {

        if ( empty( $background = get_post_meta( get_the_ID(), 'usp-custom-background_image', true ) ) ) return;
        $base = "https://example.com/img/backgrounds/";
        $extensions = array( ".jpg" , ".gif" , ".mp4" );

        foreach ( $extensions as $ext ) {

            $file = $base . $background . $ext;
            $file_headers = 

@get_headers( $file );
            if ( $file_headers[0] == "HTTP/1.1 200 OK" ) {
                $background_url = $file;
                break;
            }

        }



 if ( empty( $background_url ) ) return;

?>
    <style type="text/css">
            body { background-image: url( "<?php echo ($background_url); ?>")!important; }
        </style>
<?php
}

    add_action( "wp_head" , "rbpet_post_background" );