最新公告
  • 欢迎您光临知事网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入我们
  • WordPress函数wp_get_attachment_url()用法 获取附件URL网址

    正文概述 知事网   2020-09-17   43

    描述:

    返回附件(特色图像/文件)URL网址

    用法:

    <?php wp_get_attachment_url( $id ); ?>

    参数:

    $id
    
    (integer) (必填) 所需附件的ID
    
    默认值: None

    示例:

    if ( have_posts() ) : while ( have_posts() ) : the_post();
    if ( has_post_thumbnail() ) {
    $feat_image_url = wp_get_attachment_url( get_post_thumbnail_id() );
    echo '<div style="background-image:url('.$feat_image_url.');"></div>';
    }
    endwhile;endif;

    源文件:

    /**
    * Retrieve the URL for an attachment.
    *
    * @since 2.1.0
    *
    * @global string $pagenow
    *
    * @param int $post_id Optional. Attachment ID. Default 0.
    * @return string|false Attachment URL, otherwise false.
    */
    function wp_get_attachment_url( $post_id = 0 ) {
    $post_id = (int) $post_id;
    if ( !$post = get_post( $post_id ) )
    return false;
    
    if ( 'attachment' != $post->post_type )
    return false;
    
    $url = '';
    // Get attached file.
    if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) {
    // Get upload directory.
    if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) {
    // Check that the upload base exists in the file location.
    if ( 0 === strpos( $file, $uploads['basedir'] ) ) {
    // Replace file location with url location.
    $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file);
    } elseif ( false !== strpos($file, 'wp-content/uploads') ) {
    $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
    } else {
    // It's a newly-uploaded file, therefore $file is relative to the basedir.
    $url = $uploads['baseurl'] . "/$file";
    }
    }
    }
    
    /*
    * If any of the above options failed, Fallback on the GUID as used pre-2.7,
    * not recommended to rely upon this.
    */
    if ( empty($url) ) {
    $url = get_the_guid( $post->ID );
    }
    
    // On SSL front-end, URLs should be HTTPS.
    if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $GLOBALS['pagenow'] ) {
    $url = set_url_scheme( $url );
    }
    
    /**
    * Filter the attachment URL.
    *
    * @since 2.1.0
    *
    * @param string $url URL for the given attachment.
    * @param int $post_id Attachment ID.
    */
    $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
    
    if ( empty( $url ) )
    return false;
    
    return $url;
    }
    找互联网优质资源,上知事网!
    知事网 » WordPress函数wp_get_attachment_url()用法 获取附件URL网址

    发表评论

    发表评论

    • 323会员总数(位)
    • 407资源总数(个)
    • 32本周发布(个)
    • 0 今日发布(个)
    • 3395稳定运行(天)

    提供最优质的资源集合

    Mac软件 Dedecms源码
    升级SVIP尊享更多特权立即升级