Thursday, November 26, 2020
Home Blogging WordPress Custom Fields 101: Tips, Tricks, and Hacks

WordPress Custom Fields 101: Tips, Tricks, and Hacks

Custom fields are a helpful WordPress function that means that you can add numerous extra knowledge / data to your WordPress posts and pages.

Lots of in style WordPress plugins and themes use customized fields to retailer vital knowledge. You also can use customized fields to retailer your individual knowledge and then apply it to your web site.

In this text, we’ll present you tips on how to use WordPress customized fields with some suggestions, tips, and hacks.

Using custom fields in WordPress with practical examples

Since this can be a prolonged article, we’ve got added a desk of contents for simpler navigation.

  • What are WordPress customized fields?
  • Adding customized fields in WordPress
  • Display customized fields in WordPress themes
  • Can’t discover customized discipline in dropdown on submit edit display
  • Creating person interface for customized fields
  • Adding Custom Fields Using Advanced Custom Fields
  • Hide empty customized fields with conditional assertion
  • Adding a number of values to a customized discipline
  • Displaying posts with a selected customized key
  • Add visitor creator title utilizing customized discipline
  • Display contributors to an article utilizing customized fields
  • Display customized fields exterior the loop in WordPress
  • Display customized header, footer, sidebar utilizing customized fields
  • Manipulate RSS feed content material with customized fields
  • Manipulate RSS feed title with customized fields
  • Set expiration date for posts utilizing customized fields

What are WordPress Custom Fields?

WordPress customized fields are metadata which might be used so as to add extra data associated to the submit or web page that you’re enhancing.

By default, while you write a brand new submit, web page, or any content material sort, WordPress saves it into two completely different areas.

The first half is the physique of your content material that you simply add utilizing the submit editor.

The second half is the details about that specific content material. For instance, title, creator, date, time, and extra. This data little bit of the submit is known as metadata.

WordPress routinely provides all of the required metadata to every submit or web page you create.

You also can create and retailer your individual metadata by utilizing the customized fields.

By default, the customized fields choice is hidden on the submit edit display. To view it, you might want to click on on the three-dot menu on the top-right nook of the display and choose ‘Options’ from the menu.

Post editor options

This will carry up a popup the place you might want to verify the ‘Custom fields’ choice beneath the Advanced Panels. After that, click on on the ‘Enable & Reload’ button to reload the submit editor.

Enable and display custom fields panel

The submit editor will reload, and you’ll be capable to see the customized fields panel beneath the content material editor.

Custom fields metabox below the post editor

Custom fields can be utilized so as to add any data associated to the submit, web page, or any content material sort. This meta-information may be displayed in your theme.

However, to do that you will want to edit your WordPress theme recordsdata.

This is why this tutorial is really helpful for customers conversant in enhancing theme recordsdata. It can be useful for aspiring WordPress builders who wish to discover ways to correctly use customized fields in their very own themes or plugins.

Having stated that, let’s check out tips on how to add and use customized fields in WordPress.

Adding Custom Fields in WordPress

First, you might want to edit the submit or web page the place you wish to add the customized discipline and go to the customized fields meta field.

Adding custom field name and value

Next, you might want to present a reputation to your customized discipline and then enter its worth. Click on the Add Custom Field button to reserve it.

The discipline shall be saved and displayed within the customized fields meta field like this:

Saved custom field

You can edit this practice discipline any time you need and then click on on the replace button to save lots of your modifications. You also can delete it as wanted.

Now it can save you your submit to retailer your customized discipline settings.

Displaying Custom Fields in WordPress Themes

To show your customized discipline in your web site, you will have to edit your WordPress theme recordsdata. If you haven’t executed this earlier than, then check out our information on tips on how to copy and paste code in WordPress.

First, you will have to seek out the theme file that you might want to edit to show your customized discipline. Ideally you’d wish to show it on a single submit web page. You might want to edit the one.php or content-single.php file.

You might want to enter your customized fields code contained in the WordPress loop. Look for the road that appears like this:

1
<?php whereas ( have_posts() ) : the_post(); ?>

You wish to just remember to add your code earlier than the next line:

1
<?php endwhile; // finish of the loop. ?>

Now you might want to add this code to your theme file:

1
<?php echo get_post_meta($submit->ID, 'key', true); ?>

Don’t neglect to interchange key with the title of your customized discipline. For instance, we used this code in our demo theme:

1
<p>Today's Mood: <?php echo get_post_meta($post->ID, 'Mood', true); ?></p>

You can now save your modifications and go to the submit the place you added the customized discipline to see it in motion.

Custom field data displayed in a WordPress theme

Now you need to use this practice discipline in all of your different WordPress posts as effectively.

Simply create a brand new submit or edit an present one. Go to the customized fields meta field and choose your customized discipline from the drop down menu and enter its worth.

Reuse custom field

Click on ‘Add Custom Field’ button to save lots of your modifications and then publish or replace your submit.

Can’t Find Custom Field in Dropdown on Post Edit Screen

By default, WordPress solely masses 30 customized fields on this kind.

If you might be utilizing WordPress themes and plugins that already use customized fields, then there’s a likelihood that these will seem first within the drop-down menu and you’ll not be capable to see your newly created customized discipline.

To repair this situation, you’ll want so as to add the next code to your theme’s features.php file or a site-specific plugin.

1
2
3
4
add_filter( 'postmeta_form_limit', 'meta_limit_increase' );
function meta_limit_increase( $limit ) {
    return 50;
}

The above code will change that restrict to 50. If you continue to can’t see your customized discipline then strive rising that restrict even additional.

Creating a User Interface for Custom Fields

As you may see, that when you add a customized discipline, you’ll have to choose the sector and enter its worth every time you write a submit.

If you’ve gotten many customized fields or a number of customers writing in your web site, then this isn’t an excellent resolution.

Wouldn’t or not it’s good if you happen to may create a person interface the place customers can fill in a kind so as to add values to your customized fields?

This is what so many in style WordPress plugins already do. For instance, the search engine optimisation title and meta description field inside the favored All in One search engine optimisation plugin is a customized meta field:

All in One SEO Pack Meta Box

The easiest method to do that is by utilizing the Advanced Custom Fields plugin.

Adding Custom Fields Using Advanced Custom Fields

First factor you might want to do is set up and activate the Advanced Custom Fields plugin. For extra particulars, see our step-by-step information on tips on how to set up a WordPress plugin.

Upon activation, you might want to go to Custom Fields » Field Groups web page and click on on the add new button.

Add new field group

A discipline group is sort of a container of a set of customized fields. This means that you can add a number of panels of customized fields.

Now, you might want to present a title to your discipline group and then click on on the the ‘Add Field’ button.

Add new field

You can now present a reputation to your customized discipline and choose a discipline sort. Advanced Custom Fields means that you can create all types of fields together with textual content, picture add, quantity, dropdown, checkboxes, and extra.

Adding a new fielld

Scroll down, and you’ll see different choices for that specific discipline. You can change them to your individual necessities.

You can add a number of fields to your discipline group if you’d like. Once you might be completed, click on on the publish button to save lots of your modifications.

You can now edit a submit or create a brand new one and you’ll see a brand new panel to your customized fields beneath the content material editor.

Custom field panel on the post edit screen

For detailed step-by-step directions, see our information on tips on how to add customized meta containers in WordPress posts and submit sorts.

Hide Empty Custom Fields with Conditional Statement

So far we’ve got lined tips on how to create a customized discipline and show it in your theme.

Now let’s see tips on how to verify if the customized discipline shouldn’t be empty earlier than displaying it. To do this, we are going to modify our code to first verify if the sector has knowledge in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$mood = get_post_meta($post->ID, 'Mood', true);
if ($mood) { ?>
<p>Today's Mood: <? echo $mood; ?></p>
<?php
} else {
// do nothing;
}
?>

Don’t neglect to interchange Mood with your individual customized discipline title.

Adding Multiple Values to a Custom Field

Custom fields may be reused in the identical submit once more so as to add a number of values. You simply want to pick out it once more and add one other worth.

Adding multiple values to a custom field

However, the code we’ve got used within the above examples will solely be capable to present a single worth.

To show all values of a customized discipline, we have to modify the code and make it return the information in an array. You might want to add the next code in your theme file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$mood = get_post_meta($post->ID, 'Mood', false);
if( count( $mood ) != 0 ) { ?>
<p>Today's Mood:</p>
<ul>
<?php foreach($mood as $mood) {
            echo '<li>'.$mood.'</li>';
            }
            ?>
</ul>
<?php
} else {
// do nothing;
}
?>

Don’t neglect to interchange Mood with your individual customized discipline title.

In this instance, you’d discover that we’ve got modified the final parameter of get_post_meta operate to false. This parameter defines whether or not the operate ought to return a single worth or not. Setting it to false permits it to return the information as an array, which we then displayed in a foreach loop.

You May Also Like : How to Fix WordPress Not Sending Email Issue

Displaying Posts with a Specific Custom Key

WordPress means that you can show posts with customized keys and their values. For instance, in case you are attempting to create a customized archive web page to show all posts with particular customized keys, then you need to use WP_Query class to question posts matching these fields.

You can use the next code as a place to begin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$args = array(
    'meta_key'   => 'Mood',
    'meta_value' => 'Happy'
);
$the_query = new WP_Query( $args );
<?php
// the query
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
    <!-- the loop -->
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><?php the_title(); ?></h2>
        <?php the_content(); ?>
    <?php endwhile; ?>
    <!-- end of the loop -->
    <!-- pagination here -->
    <?php wp_reset_postdata(); ?>
<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Don’t neglect to interchange meta_key and meta_value parameters with your individual values.

Add Guest Author Name Using Custom Fields

Do you wish to add a visitor submit however don’t wish to add a brand new person profile simply so as to add a single submit? An simpler means to do this is by including visitor creator title as a customized discipline.

First, you might want to add the next code in your theme’s features.php file or a site-specific plugin.

1
2
3
4
5
6
7
8
9
add_filter( 'the_author', 'guest_author_name' );
add_filter( 'get_the_author_display_name', 'guest_author_name' );
function guest_author_name( $name ) {
global $post;
$author = get_post_meta( $post->ID, 'guest-author', true );
if ( $author )
$name = $author;
return $name;
}

This code hooks a operate to the_author and get_the_author_display_name filters in WordPress.

The operate first checks for the visitor creator title. If it exists, then it replaces the creator’s title with the visitor creator title.

Now you will have to edit the submit the place you wish to show the visitor creator title. Go to the customized fields meta field and add your visitor creator title.

Adding guest author custom field

For particulars, see our article on tips on how to rewrite visitor creator title with customized fields in WordPress.

Display Contributors to an Article Using Custom Fields

On many in style blogs and information websites, a number of authors contribute to put in writing an article. However, WordPress solely permits a single creator to be related to a submit.

One solution to resolve this downside is by utilizing Co-Authors Plus plugin. To study extra, see our information on tips on how to add a number of authors on a WordPress submit.

Another means to do this is by including contributors as a customized discipline.

First you might want to edit the submit the place you wish to show co-authors or contributors. Scroll right down to customized fields meta field and add creator names as co-author customized discipline.

Adding co-author custom field

Now add this code to your theme recordsdata the place you wish to present co-authors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
$coauthors = get_post_meta($post->ID, 'co-author', false);
if( count( $coauthors ) != 0 ) { ?>
<ul class="coauthors">
<li>Contributors</li>
<?php foreach($coauthors as $coauthors) { ?>
           <?php echo '<li>'.$coauthors.'</li>' ;
            }
            ?>
</ul>
<?php
} else {
// do nothing;
}
?>

To show creator names separated by commas, you may add the next customized CSS.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.coauthors ul {
display:inline;
}
.coauthors li {
display:inline;
list-style:none;
}
.coauthors li:after {
content:","
}
.coauthors li:last-child:after {
    content: "";
}
.coauthors li:first-child:after {
    content: ":";
}

This is the way it appeared on our demo web site.

Co-authors displayed using custom fields

Display Custom Fields Outside the Loop in WordPress

So far we’ve got proven you all of the examples the place customized fields are displayed contained in the WordPress loop. What if you happen to wanted to indicate them exterior the loop? For instance, within the sidebar of a single submit.

To show the customized fields exterior the WordPress loop add the next code:

1
2
3
4
5
6
<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'key', true);
wp_reset_query();
?>

Don’t neglect to interchange the important thing along with your customized discipline title.

Display Custom Header, Footer, Sidebar utilizing Custom Fields

Usually most WordPress themes use the identical header, footer, and sidebar on all pages. There are a number of methods to indicate completely different sidebars, header, or footer for various pages in your web site. See our information on tips on how to show completely different sidebar for every WordPress submit or web page.

One means to do that is by utilizing customized fields. Edit the submit or web page the place you wish to present a unique sidebar and then add the sidebar as customized discipline.

Adding custom sidebar to a post using custom field

Now you might want to edit your WordPress theme recordsdata like single.php the place you wish to show customized sidebar. You shall be in search of the next code:

1
<?php get_sidebar(); ?>

Replace this line with the next code:

1
2
3
4
5
6
7
<?php
global $wp_query;
$postid = $wp_query->post->ID;
$sidebar = get_post_meta($postid, "sidebar", true);
get_sidebar($sidebar);
wp_reset_query();
?>

This code merely appears to be like for the sidebar customized discipline and then shows it in your theme. For instance, if you happen to add wpbpage as your sidebar customized discipline, then the code will search for sidebar-wpbpage.php file to show.

You might want to create sidebar-wpbpage.php file in your theme folder. You can copy the code out of your theme’s sidebar.php file as a place to begin.

Manipulating RSS feed Content with Custom Fields

Want to show extra meta knowledge or content material to your RSS feed customers? Using customized fields you may manipulate your WordPress RSS feed and add customized content material into your feeds.

First you might want to add the next code in your theme’s features.php file or a site-specific plugin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function wpbeginner_postrss($content) {
global $wp_query;
$postid = $wp_query->post->ID;
$coolcustom = get_post_meta($postid, 'coolcustom', true);
if(is_feed()) {
if($coolcustom !== '') {
$content = $content."<br /><br /><div>".$coolcustom."</div>
";
}
else {
$content = $content;
}
}
return $content;
}
add_filter('the_excerpt_rss', 'wpbeginner_postrss');
add_filter('the_content', 'wpbeginner_postrss');

Now simply create a customized discipline known as “coolcustom” and add any worth you want. You can use it to show ads, pictures, textual content, or something you need.

Manipulate RSS Feed Title with Custom Fields

Sometimes you could wish to add further textual content to a submit title for RSS feed customers. For instance, in case you are publishing a sponsored submit or a visitor submit.

First you add the next code in your theme’s features.php file or a site-specific plugin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function wpbeginner_titlerss($content) {
global $wp_query;
$postid = $wp_query->post->ID;
$gpost = get_post_meta($postid, 'guest_post', true);
$spost = get_post_meta($postid, 'sponsored_post', true);
if($gpost !== '') {
$content = 'Guest Post: '.$content;
}
elseif ($spost !== ''){
$content = 'Sponsored Post: '.$content;
}
else {
$content = $content;
}
return $content;
}
add_filter('the_title_rss', 'wpbeginner_titlerss');

Next, you might want to edit the submit the place you wish to show the additional textual content within the title discipline and add guest_post and sponsored_post in customized fields.

Sponsored and guest post custom fields

If any of those two customized fields are discovered with a worth “true”, then it’s going to add the suitable textual content earlier than the title. This approach may be utilized in numerous methods to suit no matter you want.

Want to study extra cool RSS feed hacks? See our information on tips on how to add content material and manipulate your WordPress RSS feeds.

Set Expiration Date for Posts in WordPress Using Custom Fields

Want to set an expiration date for some posts in your WordPress web site? This comes helpful in conditions while you wish to publish content material just for a selected interval like operating surveys or restricted time presents.

One means to do that is by manually eradicating the submit content material or by utilizing a plugin like Post Expirator plugin.

Another means to do that is by utilizing customized fields to routinely expire posts after a selected time.

You might want to edit your theme recordsdata and add modify the WordPress loop like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
if (have_posts()) :
while (have_posts()) : the_post();
$expirationtime = get_post_meta($post->ID, "expiration", false);
if( count( $expirationtime ) != '' ) {
if (is_array($expirationtime)) {
$expirestring = implode($expirationtime);
}
$secondsbetween = strtotime($expirestring)-time();
if ( $secondsbetween >= 0 ) {
echo 'This post will expire on ' .$expirestring.'';
the_content();
} else {
echo "Sorry this post expired!"
}
} else {
the_content();
}
endwhile;
endif;
?>

Note: You might want to edit this code to match your theme.

After including this code, you may add the expiration customized discipline to the submit you wish to expire. Make certain you add the time on this format mm/dd/yyyy 00:00:00.

Adding an expiration date using custom field

Style Individual Posts Using Custom Fields

Want to vary the look of a person submit utilizing CSS? WordPress routinely assigns every submit its personal class which you need to use so as to add customized CSS.

However, utilizing customized fields you may add your individual customized lessons and then use them to model posts in a different way.

First you might want to edit a submit that you simply wish to model in a different way. Go to customized fields field and the post-class customized discipline.

Post class custom field

Next, you might want to edit your WordPress theme recordsdata and add this code at the start of WordPress loop.

1
<?php $custom_values = get_post_meta($submit->ID, 'post-class'); ?>

Now you might want to discover a line with the post_class() operate. Here is the way it appeared in our demo theme:

1
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

Change this line to incorporate your customized discipline worth, like this:

1
<article id="post-<?php the_ID(); ?>" <?php post_class($custom_values); ?>>

Now if you happen to look at the submit’s supply code utilizing Inspect instrument, then you will notice your customized discipline CSS class added to the submit class.

Custom field post class

Now you need to use this CSS class so as to add customized CSS and model your submit in a different way.

That’s all, we hope this text helped you study extra about WordPress customized fields. You can also wish to see our final step-by-step information to increase WordPress velocity and efficiency for rookies.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

70 Latest Part Time Jobs & Online Jobs from Home (Earn Rs 40,000 Per Month)

Part time jobs are an effective way to make some additional earnings from house. There are numerous half time offline jobs in addition to...

Average Merchant Navy Salary & Their Duties (By Dept & Rank)

Working in Merchant Navy may be very profitable career in India. Usually, former personnel of the Indian Navy choose to work with Merchant Navy...

25 Most Important Extra Curricular Activities for Student’s Development

In earlier days, extra curricular activities had been the one supply of leisure. Hi-tech devices equivalent to fancy LED televisions, smart-phones, laptops and computer systems...

How to Delete Naukri Profile Permanently

If you might be searching for a job and questioning which is the very best place to discover one then Naukri.com could be the...

Recent Comments