0

我有一个自定义单页single-ENG.php。我想将此页面用于带有分类的帖子language=>english。这可能吗?

4

2 回答 2

1

Yes, you can do this. The below code assumes that your Custom Taxonomy is called language and the Term to check for has the slug english (obviously change as required). Put this code in your functions.php file.

/**
 * Select a custom single template
 *
 * @param required string $single The path to the single template
 * @return string $single The updated path to the required single template
 */
function my_single_template($single){

    global $wp_query, $post;

    $terms = wp_get_object_terms($post->ID, 'language');

    if(!empty($terms)) : foreach($terms as $term) :

            if($term->slug === 'english') :
                $single = sprintf('%1$s/single-ENG.php', TEMPLATEPATH); 
            endif

        endforeach;
    endif;

    return $single;

}
add_filter('single_template', 'my_single_template');

EDIT

Having read the answer provided by @maiorano84, I agree that this isn't the best way of doing it. There are few circumstances I can think of where this technique should be used, but the fact WP have added the filter shows that they understand there may be the need, so you should be safe to use it.

于 2012-11-14T15:55:23.230 回答
1

是的,这是可能的,但我认为您需要先查看Wordpress 模板层次结构

您的方法存在一些问题:

您不应将自定义页面模板命名为“single-xxxx.php”。'single' 前缀用于单个帖子视图。这可能会使 Wordpress 感到困惑,并导致它仅在您查看帖子类型为“ENG”的单个帖子时加载模板(这可能在您的主题中不存在)。

不建议将页面用作任何类型的帖子内容的外壳。这样做的原因是,您实际上是在规避 Wordpress 提供的现有工具,以强制它使用自己的内置默认值执行它已经可以执行的操作。

与其创建一个全新的页面对象来容纳给定分类法的帖子,为什么不创建一个taxonomy-language-english.php 文件,并在主题的菜单(仪表板->外观->菜单)中设置其导航?

如果您实际注册了 Language Taxonomy,Wordpress 将自动识别新的 Taxonomy 模板并在其默认循环中查询所有适当的数据。

这详细说明了如何使用两种方法查询您的帖子。第一个是我建议使用的,只要你改变你的结构以适应良好实践的练习。第二种是将自定义模板应用于给定页面的方法。我冒昧地使用了新文件名以避免混淆 Wordpress:

使用分类语言-english.php

<?php
if(have_posts()) : while(have_posts()) : the_post();
    echo get_the_title().'<br/>'; //Output titles of queried posts
endwhile;
else :
    echo 'No posts were found'; //No posts were found
endif;
?>

使用 pagelang-english.php

<?php
/**
* @package WordPress
* @subpackage MyWordpressThemeName
* Template Name: Single English
*/
$args = array('tax_query' => array(
    array(
        'taxonomy' => 'language',
        'field' => 'slug',
        'terms' => 'english'
    )
));
$q = new WP_Query($args);
if($q->have_posts()) : while($q->have_posts()) : $q->the_post();
    echo get_the_title().'<br/>'; //Output titles of queried posts
endwhile;
else :
    echo 'No posts were found'; //No posts were found
endif;
?>

这应该足以让你开始。祝你好运。

于 2012-11-14T15:30:19.833 回答