Mez Adams Mez Adams - 2 years ago 85
PHP Question

How do I display media, URL's or PDF links with WordPress custom fields?

I am running WordPress 4.5.2, Twentysixteen, and a plugin called 'Custom Fields Template'. I am looking to make the most of WordPress' custom fields but do not know how to make it do more than display a UL with some basic text data.

I would like to know how to:

  • display an image (from Media Library),

  • an active link, and

  • an active link to a media file (e.g. Download PDF Brochure).

I like the 'Custom Fields Template' plugin as it was super easy to install, set up with the variables I need, is clean and lightweight. Here are some screenshots of what I've got so far (for a racehorse syndication website - not live):

This is the Custom Fields Template within WordPress' page edit screen.

This is the resulting code - prints image ID only.

I am comfortable with modifying WordPress's .php files but am not fluent enough with PHP to write the necessary functions from scratch.

Any help would be greatly appreciated.

Answer Source

Since you don't provide enough specifics I can only write a very generic answer.

The function the_meta() you found does not belong to the theme, it is provided by the WordPress core and as you already noticed is not very customizable, it's output can only be styled with CSS.

I assume this is the plugin you are using:
Based on that assumption you have these possibilities:

The plugin provides the shortcode [cft] you can use in the content of the post itself. It's usage is described a little bit in the plugin description, but not much.

If know that you want to show this on every post or every certain post type you can create a template file for this and call the shortcode directly using do_shortcode().

echo do_shortcode( "[cft]" );

If you don't like the output of that shortcode either, you can address the custom fields directly.

It looks like the plugin doesn't show you the field names it actually uses, so you need to find them yourself. You can do this either by looking at the database, you'll find them in the table wp_postmeta, or you add some debug output to your template file, like this:

$meta = get_post_custom( $post->ID );
var_dump( $meta );

This will show you all custom fields from the current post. You can then either use this array to print your values, or you use get_post_meta() to retrieve specific field values.

Last, but not least: You stated that you are using the default theme Twentysixteen. You should NOT edit any of these theme files, or the files from the custom field plugin. The next time they are updated all your changes are going to be lost. Instead, create a child theme and add your post templates there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download