WordPress获取附件的名字和大小

WordPress获取附件信息,比如附件的名字和大小。在网上找了一圈,不太适合我要用的场景,后面在stackoverflow上面找到了合胃口的。记录一下,也分享给你。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// retrieve file of the custom field
 $file = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);

 //get the url
 $url = $file['url'];

 //Replace url to directory path
  $path = str_replace( site_url('/'), ABSPATH, esc_url( $url) );

  if ( is_file( $path ) ){
    $filesize = size_format( filesize( $path ) );
    $filename = basename($path);
  }

            echo '<p>附件名字: ' . $filename . '</p>';
            echo '<p>附件大小: ' . $filesize . '</p>';">

上面的代码直接放在需要调用的页面即可。上面的wp_custom_attachment是附件的字段。如果你自己有自定义附件的字段,这里需要修改。比如我的字段名字叫wenjian,那么这个代码还可以这样用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// retrieve file of the custom field
 $file = get_post_meta(get_the_ID(), 'wenjian', true);

 //get the url
 $url = $file['url'];

 //Replace url to directory path
  $path = str_replace( site_url('/'), ABSPATH, esc_url( $url) );

  if ( is_file( $path ) ){
    $filesize = size_format( filesize( $path ) );
    $filename = basename($path);
  }

            echo '<p>附件名字: ' . $filename . '</p>';
            echo '<p>附件大小: ' . $filesize . '</p>';">

当然如果只用一次,这样也行。

1
2
3
4
5
6
7
8
9
10
11
12
// retrieve file of the custom field
 $file = get_post_meta(get_the_ID(), 'wenjian', true);
 //Replace url to directory path
  $path = str_replace( site_url('/'), ABSPATH, esc_url( $file) );

  if ( is_file( $path ) ){
    $filesize = size_format( filesize( $path ) );
    $filename = basename($path);
  }

            echo '<p>附件名字: ' . $filename . '</p>';
            echo '<p>附件大小: ' . $filesize . '</p>';">

参考自:https://stackoverflow.com/questions/47272813/how-to-get-the-file-name-and-file-size-for-the-attachment-of-my-custom-post-type

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this post. TrackBack URL