Find out in this tutorial how to get and display all custom fields of a WordPress entry using code.
All WordPress entries have a number of custom fields defined. These will depend on the theme and active plugins you have. And also on the Custom Post Type in question.
For example, WooCommerce uses several custom fields such as
_product_attributes and many others.
So, you might be interested in knowing all these custom fields. This information can allow you to access or list a series of posts depending on the value of a custom field.
So in this tutorial you are going to learn how to get a listing of all the custom fields in a WordPress entry.
This would be the result:
- _visibility => visible
- _stock_status => instock
- _thumbnail_id => 887
- total_sales => 0
- _downloadable => no
- _virtual => no
- _tax_status => taxable
- _tax_class =>
This is just an example of the first few lines of a WooCommerce product (product type entry).
Let’s take a look at it:
Steps to get all the custom fields of a WordPress entry
1. Create a shortcode
First you are going to encapsulate the custom fields inside a shortcode so you can display the listing wherever you want.
Add the following code at the end of functions.php or in your functionality plugin:
With this code you create a shortcode that allows you to display a list with the custom fields of the post where you add the shortcode [cf_post].
The list shows key and value pairs:
key: name of the custom field.
$value: value of the custom field.
If you prefer to be able to specify the ID of the entry for which you want the custom fields to be displayed, use this code instead:
With this modification you add a parameter to the shortcode to be able to manually add the ID of the entry.
In this list you can see all the custom fields added by themes, plugins, CPTs and even those you have added manually or using a plugin like ACF.
There is only one step left to view the list.
2. Insert the shortcode where you want
The advantage of shortcodes is that you can insert them anywhere on the web.
In the first case, you only have to type
[cf_post] where you want it to be displayed.
In the second, you will have to get the ID of the entry. You can get it by checking the URL when you edit the post or, if you want to make it easier, get it displayed directly in the WordPress admin with this tutorial.
Once you have it you just have to add it as a parameter to the shortcode. For the post with ID=21 it would look like this:
Now you know how to get and display a list with custom fields from a WordPress entry.
Any questions? I read you in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉