doupao6698
doupao6698
2018-11-23 02:45

如果第一个ACF Repeater字段为空,则打印内容

已采纳

I’m trying to make a simple document management system with ACF's repeater field. I need to print a button to download a file attached to the the top repeater field (with the size and filetype of the download). But if the top repeater field is empty, it should print “file not available” content.

I’m pretty new to PHP but this mostly works so far:

$repeater = get_field( 'document' )[0];

    if( $repeater ) {

        $fileurl = $repeater[ 'document' ][ 'url' ];
        $filesize = filesize( get_attached_file ($repeater[ 'file' ][ 'id' ]) );
        $filesize = size_format($filesize);
        $filetype = wp_check_filetype( get_attached_file ($repeater[ 'file' ][ 'id' ]));

        $download = '<div><a href="' . $repeater[ 'file' ][ 'url' ] . '">Download</a><div>' . $filesize . ' <span>' . $filetype[ 'ext' ] .'</span></div></div>' ;

                echo $download;
        }

This prints a button to the attached file in the top repeater, when there is an attached file in the top repeater. Only it prints out a dead link if there is nothing in the top repeater. This won’t do. I need to add an else condition or something so that it prints "file not available" content if there is nothing in the first repeater.

    if(empty( $repeater )) {

        $unavailable = '<div>Unavailable<div>This document isn\'t ready yet. Please check back later.</div></div>' ;

                echo $unavailable;
        }

I've tried a lot of different ways to do this, such as above, and I don't know what I'm doing wrong. Can you help?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • duanshaiduhao2471 duanshaiduhao2471 3年前

    I finally got it! I think I wasn't declaring my variables clearly enough.

    $row = get_field( 'document' );
    $first_row = $row[0];
    $first_row_file = $first_row[ 'file' ];
    
    if( $first_row_file ) :
    
                $download = '<div>Available!<div>This document is ready for download.</div></div>' ;
    
                        echo $download;
    
    else :
    
                $unavailable = '<div>Unavailable!<div>This document isn\'t ready yet. Please check back later.</div></div>' ;
    
                        echo $unavailable;
    
    endif;
    

    Now I can add more sophisticated content (like a download button) to display when there is a file to download, and a helpful message when there isn't.

    点赞 评论 复制链接分享
  • dtiopy6088 dtiopy6088 3年前
    点赞 评论 复制链接分享
  • duandao2083 duandao2083 3年前

    You have to check for a value before displaying field like that :

    if( get_field('document'){
        ... // there is an attached file
    }
    else {
        $unavailable = '<div>Unavailable<div>This document isn\'t ready yet. Please check back later.</div></div>' ;
        echo $unavailable;
    }
    
    点赞 评论 复制链接分享