Best Way to Echo Post Metadata in Module – Custom Field

Posted in: Newspaper
Post count: 23

Relatively specific, but hopefully minor request to help me get started working on a child theme. I’m modifying module 9 in a Newspaper 6 child theme and want to show a custom field (“source”). This field is a simple text string with the name of an organization which has already been attached to many existing posts.

Module 9 has this piece of code to show post author and date:


<div class="td-module-meta-info">
<?php echo $this->get_author();?>
<?php echo $this->get_date();?>
</div>

Instead of the post author, I’d like to insert the custom field for the post. Seems like it should be a simple modification, but my PHP is rudimentary at best.

Many thanks for the support.

Post count: 22421

Hi,
AS you may know, we cannot do it for you in this type of situation (custom work is not covered by support) but we can point you in the right direction. You can replace the get_author or get_date functions with this one: https://codex.wordpress.org/Custom_Fields
The codex is very useful as it describes in detail how you can use the function.
Hope this helps.
Thank you!

Post count: 23

My original call caused an error, though it’s possible I used a deprecated function. Apologies if I asked for anything above and beyond what support is meant to provide. I saw a few other examples of PHP and JS code snippets being provided on the forum, so I thought to ask.

Cheers,
Oasontu

Post count: 23

Okay, here’s the answer for anyone else who may care about inserting custom fields in modules or blocks.

I couldn’t initially display a simple custom field from a target post in a module. The usual code for displaying a custom field in WordPress is something like:

<?php echo get_post_meta($post->ID, 'your_custom_field_name',TRUE); ?>

For reference, that snippet opens php code (?php) and displays text (echo) using the WordPress get_post_meta function. The $post->ID identifies the relevant post, ‘your_custom_field_name’ is the name of your custom field, and TRUE indicates that you just want one value.

Unfortunately, using that code only showed metadata from the parent page where the module was embedded, not the post being pulled in for the module. Fortunately, the solution was stupidly simple. You just need to add $this to reference the post ID being constructed in the module. That looks like:

<?php echo get_post_meta($this->post->ID, 'your_custom_field_name',TRUE); ?>

The standard WordPress codex info is insufficient without understanding some basics on object oriented code.

Post count: 22421

Thank you Oasontu for posting this solution. I’m sure it will help many users that need it. We try to help wherever we can even if it’s custom work, but this is if the time allows us to fiddle with customization.

Post count: 3

This is exactly what I was looking for help with. Thank you!!

Viewing 6 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic.