WordPress custom post templates

New Page

Browse: Home / Theme Manual / Template Files Section / Custom Post Type Template Files

Archivos de plantilla de type de publication personalized

Themes

  • Type of publication personalized: jerarquía de plantillas
  • Personalized publication type plantillas
  • Function reference

The WordPress theme system allows custom plants for custom post types. Las plantillas personalizadas para la visualization única de publicaciones que pertenecen a tipos de publicaciones personalizadas est admissible de la version 3.0 de WordPress and the compatibility with plantillas personalizadas para visualizaciones of archives is agregó in the versión 3.1 .

Custom Post Type – Template Hierarchy

WordPress trabajará a través de la jerarquía de plantillas y usará el archivo de plantilla que encuentre primero. Entonces, if you want to create a plantilla personalizada para su acme_producttipo de publication personalizada, un buen lugar para commenzar es copie el single.phparchivo, guardarlo como single-acme_product.phpy editarlo.

Without embargo, if you do not create custom plantilla archives, WordPress uses the archives you present in your theme, que serían archives et archive.php.single.phpindex.php

Las publicaciones individuales y sus archivos se pueden mostrar usando los archivos de plantilla single.phpy respectively,archive.php

  • The individual publications of a type of publication personalized usarán single-{post_type}.php
  • y sus archivos usarán archive-{post_type}.php
  • y si no tiene esta página de archivo de tipo de publication, puede pasar BLOG_URL?post_type={post_type}

¿ Donde {post_type}está el $post_typeargumento de la función register_post_type() .

Entonces, para el ejemplo anterior, puede crear archivos single-acme_product.phpde archive-acme_product.phpplantilla para publicaciones de un solo producto y sus archivos.

Alternatively, you can use the is_post_type_archive() function to check whether the consultation will show an archive page of a certain type of publication and post_type_archive_title() to display the title of the type of publication.

Top ↑

Custom post type templates

  • single-{post-type}.php The plantilla de publication única utilizada cuando a visitor requests a publication única de un tipo de publicación personalizada. For example, single-acme_product.phpse mostly uses single posts of a custom post type called acme_product.
  • archive-{post-type}.php The plantilla de type de publication de archivo se utiliza cuando los visitantes requests a archive de type de publication personalized. For example, archive-acme_product.phpse uses to display a custom post type post archive called acme_product. Plantilla’s archive.phparchivo is used if archive-{post-type}.phpno is presented.
  • index.php gets used if none is presented a specific lookup plant ( ) for custom post type .index.phpsingle-{post-type}.php, single.php, archive-{post-type}.php , archive.php, search.php

Top ↑

Function Reference

  • register_post_type(): Registers a post type.
  • is_post_type_archive(): Comprueba if viewing an existing post type archive page.
  • post_type_archive_title(): contains or retrieves the title of a post type archive.

 

Manual Navigation

← Archivos adjuntos de plantilla Archivos de plantilla parciales y misceláneos →

diseño por volante cómo crear plantillas de publicaciones personalizadas wordpress mujer trabajando en una computer portátil cubierta de pegatinas layout by flywheel how to create custom wordpress post templates woman working on sticker covered laptop

WordPress

How to create personalized plantillas of unica publication in WordPress

Ananda Projapati design avatar Ananda Projapati Layout Avatar

Ananda Projapati — June 19, 2018

Have you ever seen a post details page with a completely different layout from other posts on the same site? That’s probably because it’s using a custom template. You can assign a custom template to individual posts, giving you increased flexibility over the appearance of your site.

Interested in learning how to create a custom single-post template? In this post, I’ll show you how you can easily create your own!

The benefit of custom templates

Before we start creating one, let’s explore why you might need a custom template and what it does.

If you want a particular post or post type to stand out from the rest of your content, you may want to consider creating a custom single-post template. This template will only be applied to the post(s) you assign it to, meaning it can have an entirely different layout than your standard posts. A unique design and layout can then increase user engagement for that particular post.

Ready to develop your own? Creating and using a custom post template is similar to a custom page template.

diseño por volante cómo crear una plantilla de publicación personalizada wordpress mujer sentada en el escritorio con una computer portátil cubierta de pegatinas flywheel layout how to create custom wordpress post template woman sitting at desk with sticker covered laptop

How to create a custom post template

I will be using the Twenty Seventeen theme for my example, but the process will be same for any theme.

Before creating a custom post template, I will first create a child theme. You can work in the main theme, but since you are creating a custom template, if you update the parent theme, you will lose your template. For this reason, it is recommended to separate your custom templates from the main theme.

For a custom template, you need to define a template name (the template name) and a template post type (where this template will be used). It looks like this:

<?php /* Template name: fullwidth post * Template post type: post*/ /*The template to display individual posts in fullwidth. */ get_header(); ?>

When you save the file, keep the file name relevant to the template name, like full-width-post.php. If you view a post from the admin panel, it will show the new template in a dropdown of the Post Attributes section.

layout by flywheel custom post template how to post attributes template fill width post layout by flywheel custom post template how to post attributes template fill width post

Our custom template is ready, but it’s not useful yet. Let’s make it a bit more beneficial!

Note: We’ll be working on multiple files, so keep track of the file names and folders.

Here’s the current layout of blog post pages in the Twenty Seventeen theme. I’m happy with that, so we’ll leave it be.

layout by flywheel custom post template how to normal post example layout by flywheel custom post template how to normal post example

Now, let’s say you want a full-width layout for a few posts. We’ll put the post title above the meta data. The meta data should have a border at the top and bottom, and both the title and meta data should be centered aligned. Here’s the wireframe:

layout by flywheel custom post template how to post title post date by author template rough mockup layout by flywheel custom post template how to post title post date by author template rough mockup

To make this layout, you need to find which file is responsible for displaying post details pages. In most themes, single.php is the file, unless there are certain predefined templates. The code structure varies from theme to theme, so it may take a little learning to understand how your particular theme works.

Once you’ve found the file that displays post details pages, you should find if a function is used to call another file or the template is created directly. In this example with the Twenty Seventeen theme, it’s get_template_part function.

The get_template_part path is the most important part to follow here.

<div class=”wrap”> <div id=”primary” class=”content area”> <main id=”main” class=”main-site” role=”main”> <?php /* Start the loop */ while ( have_posts() ): the_post(); get_template_part( ‘template-parts/post/content’, get_post_format() ); // If comments are open or we have at least one comment, load the comment template. if ( comments_open() || get_comments_number() ): comments_template(); end if; the_post_navigation( array( ‘prev_text’ => ‘<span class=”screen-reader-text”>’ . __( ‘Previous Post’, ‘twentyseventeen’ ) . ‘& ; amp; </span>< span aria-hidden=”true” class=”nav-subtitle”>’ . __( ‘Previous’, ‘twenty-seven’ ) . ‘</span> <span class=”nav-title”><span class=”nav-title-icon-wrapper”>’ . twenty-seven_get_svg( array( ‘icon’ => ‘arrow-left’ ) ) . ‘</span>%title</span>’, ‘next_text’ => ‘<span class=”text-screen-reader”>’ . __(‘Next post’, ‘twenty-seven’) . ‘</span>< span aria-hidden=”true” class=”nav-subtitle”>’ . __(‘Next’, ‘twenty-seven’) . ‘</span> & lt;span class=”nav-title”>%title<span class=”nav-title-icon-wrapper”>’ . twenty-seven_get_svg( array( ‘icon’ => ‘arrow-right’ ) ) . ‘</span></span>’, ) ); during this time; // End of the loop. ?> %title<span class=”nav-title-icon-wrapper”>’ . twenty-seven_get_svg( array( ‘icon’ => ‘arrow-right’ ) ) . ‘</span></span>’, ) ); during this time; // End of the loop. ?> %title<span class=”nav-title-icon-wrapper”>’ . twenty-seven_get_svg( array( ‘icon’ => ‘arrow-right’ ) ) . ‘</span></span>’, ) ); during this time; // End of the loop. ?>

As you can see, this refers to a path:

get_template_part( ‘template-parts/post/content’, get_post_format() );

layout by flywheel custom post template how to wordpress files on local machine layout by flywheel custom post template how to wordpress files on local machine

So the content.php file is called inside single.ph to display the post details page.

Now that you know how the single.php file works, let’s copy the code and paste it into our previously created full-width-post.php file in the child theme. Since this will be a full-width template, we’ll remove the sidebar.

layout by flywheel custom post template how to full width post file highlighted layout by flywheel custom post template how to full width post file highlighted

Now copy the content.php file from the above mentioned path. You can paste it in the same directory where your template file is, but I would suggest following the same folder structure as the parent theme.

You can keep the file name as it is, but if you ever wish to change something in the default template it’ll cause a conflict, so to avoid any issues, I’d suggest renaming the file and keeping it relevant to the template name, such as content-full-width.php.

layout by flywheel custom post template how to full width content file in post folder on local machine layout by flywheel custom post template how to full width content file in post folder on local machine

The files are in place, so now let’s modify the code to swap the post title and post meta data.

<header class=”entry-header”> <?php if ( is_single() ) { the_title( ‘ <h1 class=”entry-title”>’, ‘</h1& ;amp;gt; ‘ ); } elseif ( is_front_page() && is_home() ) { the_title( ‘ <h3 class=”entry-title”><a href=”‘ .esc_url( get_permalink() ).'” rel=”bookmark”>’, ‘</a></h3> ‘ ); } else { the_title( ‘ <h2 class=”entry-title”><a href=”‘ .esc_url( get_permalink() ) . ‘” rel=” bookmark”> ‘, ‘</a></h2> ‘ ); } if(‘post’ === get_post_type() ) { echo ‘ <div class=”entry-meta”>’; if ( is_single() ) { twenty-seven_posted_on(); } else { echo twenty-seven_hour_link(); twenty-seven_edit_link(); }; echo ‘</div> <!– .entry-meta –>’; }; ?> </header> <!– .entry-header –> ; if ( is_single() ) { twenty-seven_posted_on(); } else { echo twenty-seven_hour_link(); twenty-seven_edit_link(); }; echo ‘</div> <!– .entry-meta –>’; }; ?> </header> <!– .entry-header –> ; if ( is_single() ) { twenty-seven_posted_on(); } else { echo twenty-seven_hour_link(); twenty-seven_edit_link(); }; echo ‘</div> <!– . entry-meta –>’; }; ?> </header> <!– .entry-header –>

Pour utiliser ce modèle, modifiez le message souhaité à partir de l’administrateur WordPress et attribuez le modèle à partir du menu déroulant.

layout by flywheel custom post template how to full width post custom template selected in wordpress layout by flywheel custom post template how to full width post custom template selected in wordpress

Si vous vérifiez le message sur le front-end, il n’est toujours pas en pleine largeur, mais le titre et les métadonnées ont changé de place, nous savons donc que le message utilise notre modèle personnalisé

layout by flywheel custom post template how to full width website screenshot layout by flywheel custom post template how to full width website screenshot

Nous devons ajouter du CSS pour le rendre en pleine largeur. WordPress génère automatiquement une classe selon le nom du modèle dans la section du corps.

layout by flywheel custom post template how to full width post with inspect website screenshot layout by flywheel custom post template how to full width post with inspect website screenshot

Utilisez cette classe pour cibler ce modèle particulier. Vous pouvez ajouter le CSS au fichier style.css du thème enfant.

.post-template-full-width-post.has-sidebar:not(.error404) #primary{ float:none; width: automatic; } .post-template-full-width-post .entry-header{ text-align:center; lower margin: 1.3 em; } .post-template-full-width-post .entry-meta{ border-top:1px solid #ccc; border-bottom: 1px solid #ccc; padding: 15px 0; }

Now we have the layout as we wanted. Any post using this template will have this exact same style.

layout by flywheel custom post template how to full width post layout by flywheel custom post template how to full width post

You can create as many custom templates as you want to fit your requirements. You can even create templates based on post categories.

Can I use a plugin for this?

If you are not comfortable with PHP codes, then you can use some plugins, but I must admit, there are very few plugins available for creating custom post templates and most of them are not very useful because you have to manually create the template anyways.

I have found the Post Custom Templates Lite plugin very useful. It’s a free plugin that allows you to create post templates without any coding in a nice drag-and-drop interface. It has lots of customization options, so if you want to customize a post template, in general this plugin can help you out.

Note: The free version only allows your to customize normal post templates. You have to use the pro version to be able to create custom post templates and get some additional features.

layout by flywheel how to create custom post template wordpress man typing on laptop sitting on blue couch with dog layout by flywheel how to create custom post template wordpress man typing on laptop sitting on blue couch with dog

Conclusion

Whether you work manually or use a plugin to create a custom single post template, it allows your most important posts to stand out from the rest. For inspiration, check out Brian Dean’s site; he uses a particular template for his definitive guide posts to make them look unique from rest of his posts.

So, give it a try and create your own unique single-post template.

All photography in this article was shot in-house at Flywheel.

svg%3E flywheel-convince-your-client-managed-wp-hosting-mockup

Still need to convince your clients?

Convincing your clients that managed WordPress hosting is right for their business is no easy feat. To help your mission, we’ve packaged up a couple of one-sheeters explaining the value of managed hosting that you can pass straight to your client. Download it here!

What are you going to learn next? Try one of these tutorials!

  • How to choose the best CSS units to create better site layouts
  • How to add a responsive Google Map in WordPress
  • How to efficiently migrate your sites from Adobe Business Catalyst to WordPress (+ over 20 resources!)

Share this article

  • Subscribe
    • Get the inspiration you need to do your best work, every Sunday!

  • How to customize WordPress
  • Tutorials

How to Create Custom Single Post Templates in WordPress

Last updated on September 1st, 2022 by Editorial Staff | Reader DisclosureDisclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.

Shares 1k Share Tweet Share Facebook Messenger WhatsApp Email

Do you want to create a custom single post template in WordPress?

Custom single post templates allow you to use different layouts for your individual blog posts. Many WordPress themes come with a few different page templates, and you can also create your own if needed.

In this article, we’ll show you how to easily create custom single post templates in WordPress. We’ll share multiple methods, so you can choose one that works best for your needs.

How to Create Custom Single Post Templates in WordPress How to Create Custom Single Post Templates in WordPress

When Do You Need a Custom Single Post Template?

Sometimes you may want a different look and feel for certain posts on your WordPress website. For instance, you may want to use a different layout for featured articles or stories in a particular category.

This is where you need a custom single post template in WordPress.

By default, WordPress uses the single post template based on the WordPress template hierarchy. All themes come with a single.php template, and this is used by default for all of your single posts.

Some themes may also include additional templates or layout choices that you can use.

It is very much like creating a custom page template. Most WordPress themes also come with page templates that you can use while editing a post or page in WordPress.

Choosing a Page Template Choosing a Page Template

Having said that, let’s take a look at how to easily create custom single post templates in WordPress. We’ll show you multiple methods, so you can use the one that works best for you.

  • Creating single post templates using the block editor
  • Creating custom single post templates using SeedProd
  • Using theme settings to create single post layouts
  • Manually creating custom single post templates with code
  • Creating custom single post templates by category
  • Creating custom single post templates for specific authors

Creating Single Post Templates Using the Block Editor

This method does not really create a post template and is limited in flexibility. However, it is the easiest way to save your own single post layouts and then reuse them.

The default WordPress block editor comes with a built-in feature that allows you to save and reuse blocks. One such reusable block is the group block.

The group block allows you to put several blocks and entire post layouts into one group. You can then save this group block and reuse it in your other posts.

Let’s take a look at how to use the group block to save your custom post templates.

First, you need to create a new post in WordPress. After that, simply add a group block to the content area.

Add Group Block Add Group Block

Now you can start adding blocks into the group block to create a single post layout for your WordPress blog.

You can add any blocks you want including columns, media and text, cover images, and more.

Add Blocks to the Group Add Blocks to the Group

Once you are satisfied with the layout you have created, you need to take your mouse up and select the group block.

Simply click on the three-dot menu icon and then select the ‘Add to Reusable blocks’ option.

Add Reusable Block Add Reusable Block

Next, you need to provide a name for the reusable block and then click on the Save button. WordPress will now save your reusable block including all the blocks inside the group block.

You can then edit any existing post on your website or create a new one. On the post edit screen, simply click on the add new block button and look for your saved block under the ‘Reusable’ tab.

Reuse Block Reuse Block

Add the block to your post and WordPress will load your entire group block with all the blocks and settings as you saved them.

This method allows you to save your custom layouts. However, it does not allow you to change how your theme handles single posts.

If you would like greater flexibility, then continue reading the next step.

Creating Custom Single Post Templates Using SeedProd

The easiest way to create a custom single post template is by using SeedProd. It’s the best WordPress website builder plugin and can create beautiful website layouts and custom templates without writing any code.

You can use SeedProd’s drag-and-drop builder to create a fully custom WordPress theme, including custom single post templates.

The first thing you need to do is install and activate the SeedProd plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to enter your license key. You can find this information under your account on the SeedProd website.

SeedProd license key SeedProd license key

After that, it’s time to create a custom WordPress theme. This is much simpler than it sounds.

Creating a Custom WordPress Theme

First, you need to head over to the SeedProd » Theme Builder page. Here, you’ll use one of SeedProd’s ready-made themes as a starting point. This will replace your existing WordPress theme with a new, custom design.

You can do that by clicking the ‘Themes’ button.

Create your custom theme Create your custom theme

You will be shown a list of professionally designed themes that are designed for different types of websites. For example, there are templates called ‘Modern Business’, ‘Marketing Agency’, and ‘Mortgage Broker Theme’.

Take a look through the options and select one that best matches your needs by clicking the checkmark icon.

Select a Theme That Matches Your Needs Select a Theme That Matches Your Needs

Once you have chosen a theme, SeedProd will generate all the theme templates you need, including one for single pages and another for single posts.

Each template comes set up with attractive layouts and placeholder content that’s easy to customize.

SeedProd Creates All the Templates You Need for Your Theme SeedProd Creates All the Templates You Need for Your Theme

To learn more about creating a theme with SeedProd, see our guide on how to easily create a custom WordPress theme without any code.

Customizing the Default Single Post Template

SeedProd makes it easy to customize the default ‘Single Post’ template using a drag and drop page builder.

Simply click the ‘Edit Design’ link found under the template. This will open your post template in SeedProd’s visual editor.

Click the 'Edit Design' Link Under the Single Post Template Click the 'Edit Design' Link Under the Single Post Template

SeedProd’s visual editor has a 2 column layout. On the left, you’ll find blocks and sections that you can add to your design. And on the right is a preview of the template where you can see your changes in real-time.

SeedProd Visual Editor Blocks and Sections SeedProd Visual Editor Blocks and Sections

It’s also easy to customize the layout of your post template. Simply click on any block to see its settings in the left column.

For example, if you click on the post title, then you’ll be able to see its settings. Now you can change the alignment, font size, heading level, and more.

Click on a Block to Change Its Settings Click on a Block to Change Its Settings

Clicking the Advanced tab lets you change font colors, spacing, and other styles.

You can add additional blocks by dragging them from the left column into the preview column. SeedProd uses template tags to pull in dynamic content like post titles, featured images, comments, and more. This lets you add content to the template without having to edit each post individually.

For example, you can add a Posts block at the end of your post content. This will display recent posts that your visitors may wish to read when they finish the current post. This block will be shown automatically on all posts using this template.

Add a Posts Block to the Bottom of Your Single Posts Template Add a Posts Block to the Bottom of Your Single Posts Template

Next, you can change the settings of the Posts block to customize the content that is shown.

For example, you can display content from specific categories, use a two-column layout, and change the number of posts that are shown.

SeedProd Posts Block Settings SeedProd Posts Block Settings

Feel free to spend time experimenting with different blocks and exploring their settings.

After creating something you’d like to use as your post template, it is time to save it by clicking the green ‘Save’ button in the top right corner. After that, you can close the SeedProd visual editor by clicking the ‘X’ close icon.

When You're Finished, Save the Single Post Template When You're Finished, Save the Single Post Template

You can customize the rest of your WordPress theme in the same way. But if you need a little help, then refer back to our step-by-step guide on how to create a custom WordPress theme with SeedProd.

When you’re happy with how everything looks, make sure the ‘Enable SeedProd Theme’ switch is toggled to the on position. Your WordPress site will now use your SeedProd theme and custom single post template.

Enable the SeedProd Theme Enable the SeedProd Theme

Using Theme Settings to Create Custom Single Post Layouts

Many popular WordPress themes come with built-in settings to customize the appearance of your single post template.

If your theme supports these settings, then you’ll be able to find them on the post edit screen. The options available may change depending on the theme you are using.

For instance, the Astra theme offers customization options when editing a single post. Using these options, you can change sidebars, hide headers, title, menus, and more.

Astra Theme Single Post Template Customization Astra Theme Single Post Template Customization

On the other hand, many of the top WordPress themes come with ready-to-use templates that you can use.

If your theme includes single post templates, then you will find them under the ‘Template’ or ‘Post Attributes’ panel while editing a post.

Choose a template when writing a single article Choose a template when writing a single article

These templates are complete layouts that you can use with no configuration required.

Manually Creating Custom Single Post Templates With Code

This method is a bit advanced as it requires you to edit theme files, copy and paste code, and optionally add custom CSS. If you haven’t done this before, then check out our tutorial on how to copy and paste code in WordPress.

First, you need to open a plain text editor on your computer like Notepad and paste the following code inside it:

1

2

3

4

5

6

7

<?php

/*

  * Template Name: Featured Article

  * Template Post Type: post, page, product

  */

   

  get_header();  ?>

This code defines a new template called ‘Featured Article’ and makes it available for post, page, and product post types.

You should save this file as wpb-single-post.php on your desktop. Next, you need to add the template to your WordPress site. To do that, you need to use an FTP client to upload the file to your current theme folder.

Now you can log in to your WordPress admin area and create or edit a post. Scroll down a little on the post edit screen, and you will notice a new ‘Template’ panel or ‘Post Attributes’ meta box with an option to select the template.

Select your custom post template Select your custom post template

You will see your ‘Featured Article’ custom template listed there.

Right now your template is essentially empty so selecting it will simply display a white screen.

Let’s fix this.

The easiest way to do that is by copying the code from your theme’s single.php file and using it as a starting point. You’ll have to open the single.php file and then copy everything after the get_header() line.

Next, you need to paste this code at the end of your wpb-single-post.php file. Now you can save this file and upload it back to your server.

However, this will look exactly the same as your current single post template. You can now start making changes to your custom single post template.

You can add your own custom CSS classes, remove sidebars, create a full width template, or anything you want.

Creating Custom Single Post Templates by Category

Would you like to use a custom single post template based on categories? For example, you can give posts in the travel category a different layout to posts in the photography category.

You can do that using either the SeedProd Theme Builder or code.

Creating Custom Single Post Templates by Category Using SeedProd

Earlier we covered how to customize the SeedProd Theme Builder’s default single post template. But it doesn’t stop there. With SeedProd you can add as many custom post templates as you like, such as a different layout for every post category.

To add a new single post template, just click the ‘Duplicate’ link under the original post template. A new template called ‘Single Post – Copy’ will be created and added to the top of the theme templates page.

Create a new plantilla de publication duplicando la plantilla de publication predeterminada Create a new post template by duplicating the default post template

You can customize the new template in the same way you customized the default Single Post template earlier. Simply click the template’s ‘Edit Design’ link and make any changes you like using SeedProd’s visual editor.

When you’ve finished customizing the template, you will need to add some conditions so that SeedProd will know which posts should use this template. In this case, we want it displayed when viewing posts within a single category.

Haga click on el enlace 'Change conditions' Click on the "Edit Terms" link

You can do that by clicking the template’s ‘Edit Conditions’ link and a new window will pop up.

Here you can give the template a name and priority. The default Single Post template has a priority of 0, so make sure you give this template a higher priority so it will be displayed on matching categories.

Agregar condiciones para mostrar la plantilla para una determinada categoría Add conditions to display the model of a certain category

Under ‘Conditions’, select ‘Has Category’ from the second drop down menu, then type the name of the category in the last field. For example, if you only want posts from the photography category to use this layout, then type ‘photography’.

When you’re finished, click the ‘Save’ button and now this template will be used for all posts in the matching category.

This is the easiest way to create multiple custom post templates in WordPress. It doesn’t require any knowledge of code and won’t accidentally mess up any theme files.

Creating Custom Single Post Templates by Category Using Code

This is another method for those who are comfortable adding code to their theme files.

First, you need to add this code to your theme’s functions.php file or a code snippets plugin.

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

28

29

30

/*

* Define a constant path to our single template folder

*/

define(SINGLE_PATH, TEMPLATEPATH . ‘/single’ );

  

/**

* Filter the single_template with our custom function

*/

add_filter( ‘single_template’ , ‘my_single_template’ );

  

/**

* Single template function which will choose our template

*/

function my_single_template( $single ) {

global $wp_query , $post ;

  

/**

* Checks for single template by category

* Check by category slug and ID

*/

foreach (( array )get_the_category() as $cat ) :

  

if ( file_exists (SINGLE_PATH . ‘/single-cat-‘ . $cat ->slug . ‘.php’ ))

return SINGLE_PATH . ‘/single-cat-‘ . $cat ->slug . ‘.php’ ;

  

elseif ( file_exists (SINGLE_PATH . ‘/single-cat-‘ . $cat ->term_id . ‘.php’ ))

return SINGLE_PATH . ‘/single-cat-‘ . $cat ->term_id . ‘.php’ ;

  

endforeach ;

}

This code first checks to see if WordPress is requesting a single post. If it is, then it tells WordPress to look for the template in the /single/ folder of your WordPress theme.

Now you need to add template files defined by this code.

Connect to your WordPress hosting using an FTP client or File Manager in cPanel and go to /wp-content/themes/your-theme-folder/.

Inside your current theme folder, you need to create a new folder called ‘single’. Next, you need to open this folder and create a new file inside it. Go ahead and name this file single-cat-{category-slug}. Replace {category-slug} with your actual category slug.

For example, if you have a category called ‘News’, then you will create single-cat-news.php file. If you have a category called ‘Travel Tips’, then create a template single-cat-travel-tips.php, and so on.

Creating a Single Post Plant for Categories Creating a Single Post Template for Categories

Ahora, estos archivos de plantilla estarán totalmente vacíos. Como punto de partida, puede copiar el contenido de su archivo single.php de la carpeta de su tema y pegarlo dentro de cada una de estas plantillas. Después de eso, deberá editar estas plantillas para realizar los cambios deseados.

Una vez que haya terminado, puede ir a su sitio web y ver una publicación. Utilizará la plantilla que ha creado para la categoría en la que está archivada esta publicación.

Ahora supongamos que tiene una publicación archivada en dos categorías Noticias y Consejos de viaje. WordPress mostrará automáticamente la plantilla para ‘Noticias’ porque aparece primero en orden alfabético.

Por otro lado, si archivó una publicación en una categoría y no creó una plantilla para esa categoría, WordPress volverá a la plantilla single.php predeterminada de su tema.

Création de plantillas personalizadas de publicación única para autores específicos

Supongamos que desea que las publicaciones escritas por un autor específico se vean diferentes en su sitio web. Puede hacerlo usando código siguiendo la misma técnica que mostramos para las categorías.

Primero, debe agregar ise código al archivo functions.php of its theme or a complement of fragments of código.

1

2

3

4

5

6

seven

8

9

ten

11

12

13

14

15

dieciseis

17

18

19

20

21

22

23

24

25

26

27

28

29

/**

* Set a constant path to our unique templates folder

*/

set(SINGLE_PATH, TEMPLATEPATH. ‘/single’);

  

/**

* Filter the single_template with our custom function

*/

add_filter(‘single_template’, ‘my_single_author_template’);

  

/**

* Unique pattern function which will choose our pattern

*/

function my_single_author_template( $single ) {

global $wp_query, $post;

  

/**

* Checks unique model per author

* Check by username and ID

*/

$curauth = get_userdata( $wp_query ->post->post_author);

  

if (file_exists(SINGLE_PATH.’/single-author-‘.$curauth->user_nicename.’.php’))

returns SINGLE_PATH . ‘/single-author-‘ . $curauth->user_nicename . ‘.php’;

  

elseif(file_exists(SINGLE_PATH.’/single-author-‘.$curauth->ID.’.php’))

returns SINGLE_PATH . ‘/single-author-‘ . $curauth->ID . ‘.php’;

  

}

Then, debe conectarse su site web mediante FTP o el administrador de archivos cPanel en cPanel y luego ir a /wp-content/themes/your-theme-folder/. If aún no ha creado una carpeta llamada /single/ dentro de ella, continue y creado la ahora.

Dentro de esta carpeta, debe crear una plantilla utilizando el nom de usuario del autor en el nom de la plantilla. For example, single-author-johnsmith.php.

Esta plantilla estará vacía, por lo que puede copie y pegar el contenido de la plantilla single.php de su tema y usarla como point de partida.

Ahora can visit his website to see a publication created by a specific author. Use the plant you created.

Hope that is articulated the haya ayudado a learn how to create personalized seedlings of individual publications in WordPress. It is also possible that you want to learn how to carry out a seguimiento de los visitors del site web sur site de WordPress, over nuestra lista de complementos de WordPress que debe tener para hacer crecer sur site.

If you like this article, submit to a new YouTube channel for WordPress video tutorials. Also puede encontrarnos on Twitter and Facebook .

Shares 1k Share Tweet Share Facebook Messenger WhatsApp Email


Video WordPress custom post templates

Related Posts

Free chat room code for my website

Contents1 How to set up a free chat room on the website.2 3 comentarios2.1 Trackbacks/Pingbacks2.2 Submit a Comment Cancel reply3 How to Create a Chat Room Website…

Background image full screen css

Contents1 Cómo – Full Page Image1.1 Example1.2 Example2 CSS background image tamaño tutorial: how to codify a complete page background image3 Perfect Full Page Background Image3.1 Méthode CSS géniale,…

WordPress leverage browser caching

Contents1 Aproveche el almacenamiento in hidden del navegador1.1 Will it works for my website?1.2 Where are plugin options1.3 Some JavaScript files still display under Leverage Browser Caching1.4…

WordPress post to facebook page

Contents1 How to Automatically Post to Facebook from WordPress1.1 Download Now: How to Launch a WordPress Website [Free Guide + Checklist]1.2 1. Create an IFTTT account.1.3 2….

Download images from wordpress media library

Contents1 How to export your WordPress media library1.1 Download maintenant : How to launch a WordPress website [Free Guide + Checklist]1.2 How to export your WordPress media…

WordPress single post template

Contents1 How to Create Custom Unique Post Templates in WordPress2 Post Template Files2.1 author.php2.2 Fecha.php3 Handbook navigation4 How to Create Custom Single Post Templates in WordPress5 Video…