在WordPress中为帖子添加自定义功能?

时间:2011-09-19 19:31:13

标签: php wordpress function

我非常喜欢自定义帖子模板插件,我想把它构建到我的主题中。

函数can be found here,但它仅适用于页面。如何让这个也适用于帖子?

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;' ));

1 个答案:

答案 0 :(得分:0)

根据您链接的网站,这应该适用于帖子和页面。此外,根据WordPress文档(http://codex.wordpress.org/Plugin_API/Filter_Reference/_single_template),'single_template'过滤器用于帖子和页面。

您是否有一个单独的single.php文件,其名称中包含正确的类别ID?例如单2.PHP

如果找不到正确命名的single.php文件,它将恢复为标准的single.php文件。这就是你所看到的吗?

编辑:

如果您想在Wordpress管理区域中实际使用此选项,我建议使用Post Meta来存储您要使用的single.php文件的值。

您可以将自定义元框添加到管理页面http://codex.wordpress.org/Function_Reference/add_meta_box,然后您可以使用原始问题中的一些代码获取所有可用的single.php模板文件,并将其放入下拉列表中:

$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";
}

然后,您需要添加类似于原始过滤器的过滤器:

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');