Working on a publication (wordpress based) website, having a custom post type "article" with custom taxonomy : language (with only two options: French, English). I made a custom post type template (single-article-french.php) for only French language articles (English ones will be displayed using the single-cpt.php template). How can i make wordpress change automatically the template of my custom post type to single-article-french.php when the language of the article is set to French?
1 Answer
What you would do, is have your default single-article.php
. This will get called by default because of the WP permalinks and templating system.
At the top of your single-article.php
do the following before your get_header()
call:
<?php
$language = get_the_terms( get_the_ID(), 'language' );
if ( ! is_wp_error( $language) && $language && 'French' == $language[0]->name ) {
get_template_part( 'single-article-french' );
} else {
// english template stuff
get_header();
// etc.
}
That way you will call single-article-french.php
when the French category is selected.
-
thanks for your response. i got this : Fatal error: Cannot use object of type WP_Error as array in this line:
if ( count( $language ) && 'French' == $language[0]->name ) {
.– nisrCommented Aug 5, 2015 at 14:43 -
1We better add the
is_wp_error( $language )
check as well, just in case. @nisr Most likely you got this error because it should beget_the_terms()
instead ofget_terms()
. But then we must be careful here withcount( $language )
for no terms, becausecount( false )
is1
!! ;-)– birgireCommented Aug 5, 2015 at 15:48 -
thanks @birgire. can you give your full suggested code please?– nisrCommented Aug 5, 2015 at 16:02
-
1it worked perfectly .. thanks a lot @birgire and thanks to Eric– nisrCommented Aug 5, 2015 at 17:41
-
1Thanks for the cleanup, @birgire, this answer was pre-coffee :). Commented Aug 5, 2015 at 18:39