I'm trying to format my single post page template that has custom types. I'm using the_content() which displays the post contents altogether, but how can I call individual content fields so that I can arrange them in the template?
functions.php
function stories_init() {
$args = array(
'label' => 'Stories',
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array('slug' => 'stories'),
'query_var' => true,
'menu_icon' => 'dashicons-video-alt',
'supports' => array(
'title',
'editor',
'custom-fields',
'thumbnail',)
);
register_post_type( 'stories', $args );
}
single-post.html
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php endwhile; ?>
You would need to create custom fields to be used in posts if you wanted to separate out parts of your content, like each paragraph individually or something. the_content()
will always print out the entire content.
If you want a plugin to do it, this is the most popular https://wordpress.org/plugins/advanced-custom-fields/
Or, when creating a new post, you can go to the top and click Screen Options
then check the Custom Fields box
.
Custom fields will appear under your post content box. You can create a new one and give it a value (They act as key/value pairs).
to call it in your template, use <?php echo get_post_meta($post_id, $key, $single); ?>
$post_id
-> is the ID of the post you want the meta values for. Use $post->ID
to get a post's ID within the $post
variable scope. Use get_the_ID()
to retrieve the ID of the current item in the WordPress Loop.
$key
-> is a string containing the name of the meta value you want.
$single
can either be true
or false
. If set to true then the function will return a single result, as a string. If false, or not set, then the function returns an array of the custom fields.
Since the name of your Custom-Post is stories
, you are better-off creating a specialized File with the name: single-stories.php
inside your theme's directory. Inside that file you could do something like this:
<?php
// FILE-NAME: single-stories.php
if ( have_posts() ) :
while ( have_posts() ) : the_post(); $id= get_the_ID(); // IN CASE YOU NEED IT ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<span class="entry-author"><?php echo get_the_author(); ?></span>
<span class="entry-date"><?php echo get_the_date(); ?></span>
<!-- YOU CAN DO AS YOU WISH IN THIS FILE -->
<!-- AND THE RENDERING HERE WILL BE UNIQUE TO THE CUSTOM STORIES POSTS -->
<!-- HOWEVER, BE INFORMED THAT THIS IS FOR DETAILED (SINGLE-POST) VIEW ONLY -->
<?php endwhile; ?>
<?php endif; ?>