简体   繁体   中英

Print content if first ACF Repeater field is empty

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?

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM