Output the description for a file field from the linked media post if available

When you add a file field to a post an entry is added in the Media Library, where a description can be set.

When outputting such a field there is no way to retrieve the description to be used, for example, as the text of a link to the file.

We can add a custom shortcode for this with the following code. The ‘description’ shortcode needs the field attribute which specifies the slug of the file field. If no description is available it will fallback to the URL itself.

add_shortcode('description', function ($atts = [], $content = null) {

	// provide default wpcf- prefix
	$atts = shortcode_atts(
		array(
			'prefix' => 'wpcf-',
			'field' => '',
		),
		$atts
	);

	global $post;
	$output = '';

	if (isset($atts['field'])) {

		$url = get_post_meta($post->ID, $atts['prefix'] . $atts['field'], true);

		// get the ID of the media post for this URL
		$media_id = attachment_url_to_postid($url);

		$media = get_post($media_id);

		if (strlen($media->post_content) == 0 || strlen($media->post_content) == null) {
			$output = $url;
		} else {
			$output = $media->post_content;
		}

	}

	return $output;
});

You could then construct such a link (for a field ‘document’) like so:

[description field='document']

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments