首页 > 解决方案 > 在将文件加载到网页之前检查文件是否存在

问题描述

我构建了一个 php 函数,它根据自定义字段中指定的内容更改 WordPress 帖子的背景,例如 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 文件是否存在......这可能吗?不知何故?

标签: phpwordpressbackground

解决方案


这可能是一种方法。

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。


推荐阅读