最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

templates - Templating of a specific post ID

programmeradmin0浏览0评论

I'd like to know it's possible to do something like this

single-post-45.php

I needn the post(45) only to have a custom template.

I know we can achieve this with page, like this

page-45.php

or by a templating file template-test.php

But I can't find if it's possible to do this with simple post (following the wordpress hierarchie, i think it's not possible)

.jpg

I'd like to know it's possible to do something like this

single-post-45.php

I needn the post(45) only to have a custom template.

I know we can achieve this with page, like this

page-45.php

or by a templating file template-test.php

But I can't find if it's possible to do this with simple post (following the wordpress hierarchie, i think it's not possible)

https://www.lafabriquedunet.fr/wp-content/uploads/2018/02/templates-wordpress-hierarchie.jpg

Share Improve this question asked Feb 9, 2021 at 11:13 lucrecelucrece 1248 bronze badges 1
  • what are you trying to achieve that requires that specific post to have a different template? – Tom J Nowell Commented Feb 9, 2021 at 11:59
Add a comment  | 

1 Answer 1

Reset to default 4

You have to follow this file name structure:

single-{post-type}-{slug}.php

If you have a post names "Hello World" and the slug of post is hello-world then the template name will be single-post-hello-world.php

Update:

There is no default way to use id in template name. But you might try this snipped:

<?php
add_filter( 'single_template', 'load_post_template_by_id' );
 
function load_post_template_by_id( $single_template ) {
    global $post;
 
    if ( 'post' === $post->post_type) {
        $tmp_template = dirname( __FILE__ ) . '/single-post-'.$post->ID.'.php';

        if ( file_exists( $tmp_template ) ) {
            $single_template = $tmp_template;
        }
    }
 
    return $single_template;
}

Here I'm overriding the post template in a tricky way. Now if you have a post with id 42 and you have a template file named single-post-42.php then it should load automatically.

I didn't test the code. So use it with your own risk.

发布评论

评论列表(0)

  1. 暂无评论