How to output File Upload Field Type as link with filename as label/caption through custom ShortCode

functions.php

<?php
add_shortcode('listing_custom_file_output', 'listing_custom_file_output_filename_link');

function listing_custom_file_output_filename_link( $atts, $content = ''){
	
	// !! WARNING !!
	// When using the core WordPress `get_post_meta` you MUST prepend the meta key
	// with an underscore.  So if the meta key was listing_custom_file, below it 
	// needs to be _listing_custom_file
	$file_paths = get_post_meta( get_the_ID(), "_listing_custom_file")
    
    if( empty( $file_paths ) ) return;
    
	ob_start();
	
	// Array means multiple files allowed in upload
	if( is_array( $file_paths ) ){
		
		foreach( $file_paths as $file_path ){
			echo "<a href='{$file_path}' target='_blank'>" . basename( $file_path ) . "</a>";
		}
		
	} else {
		
		// Otherwise is just a single file upload field
		echo "<a href='{$file_paths}' target='_blank'>" . basename( $file_paths ) . "</a>";
		
	}
	
	$output = ob_get_clean();
	
	return $output;
}
No comments yet.

Leave a Reply