开发者

Add Custom Function to Posts in WordPress? [closed]

Closed. This question is off-topic. It is not currently accepting answers.

Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 11 years ago.

Improve this question

I love the Custom Post Templates plugin so much I want to build it into my themes.

The function can be found here, but it only works for pages. How do I get this to also work for posts?

add_filter('single_template', create_function('$t', 'foreach( (array) get_the_category() as $cat ) { if ( file_exists(TEMPLATEPATH . "/single-{$cat->term_id}.php") ) return TEMPLATEPATH . "/single-{$cat->term_id}.php"; } return $t;'开发者_如何学运维 ));


According to the website you linked, this should work for posts and pages. Also, according to the WordPress docs (http://codex.wordpress.org/Plugin_API/Filter_Reference/_single_template), the 'single_template' filter is used for both posts and pages.

Do you have a separate single.php file with the correct category ID in the name? e.g. single-2.php

If no correctly named single.php file is found, it will revert back to the standard single.php file. Is this what you're seeing?

EDIT:

If you wanted this option actually in the Wordpress Admin area, I would suggest using Post Meta to store the value of the single.php file you want to use.

You could add a custom meta box to the admin page http://codex.wordpress.org/Function_Reference/add_meta_box then you could use some of your code from your original question to get all the available single.php template files, and drop them into a drop down list:

$templates = array();
foreach( (array) get_the_category() as $cat ) { 
    if ( file_exists(TEMPLATEPATH . "/single-{$cat->term_id}.php") ) 
        $templates[] = TEMPLATEPATH . "/single-{$cat->term_id}.php";
}

You would then need to add a filter similar to your original one:

function custom_single_template($t){
    global $post;

    if( get_post_meta($post->ID, 'name_of_key', true) ) {

      return TEMPLATEPATH . get_post_meta($post->ID, 'name_of_key', true);

    }

    return $t;

}
add_filter('single_template', 'custom_single_template');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜