Modèle unique personnalisé pour une catégorie spécifique
-
-
Mon avis,utilisez ce avec quoi vous êtes à l'aise.S'il y a une différence deperformance,ce seraminime/sansimportance.Mapréférence,utilisez lefiltreMy opinion, use what you are comfortable with. If there are any performance difference it will be minute/irrelevant. My preference, use the filter
- 0
- 2014-11-29
- Pieter Goosen
-
Thxpour la réponse rapide.Uneidée commentincluretous les sous/parents,etc.J'ai réaliséen cemoment que celane montrait que le chatprincipal ...Thx for the quick response. Any idea how to include all the sub/parent and so on categries to? I realized right now it only shows the main cat...
- 0
- 2014-11-29
- NewUser
-
4 réponses
- votes
-
- 2014-11-29
Demon commentaire au PO
Mon avis,utilisez ce avec quoi vous êtes à l'aise. S'il y a une différence deperformance,ce seraminime/sansimportance. Mapréférence,utilisez lefiltre
Pouren venir à votre véritablepréoccupation/question,àmon avis,lameilleure approche sera d'utiliser l'identifiant de la catégorieparentet detravailler àpartir de là. Ce sera lemoinsgourmanden ressourcespourtravailler àpartir d'ici. L'ingénierieinversepeut devenir ungaspillage de ressourcestout àfaitinutile.
Utilisez
get_categories
pour obtenir les catégoriesenfants du catégorie donnée. Vouspouvez utiliser l'un des deuxparamètres,soitparent
ouchild_of
parent (entier)
N'affichez que les catégories qui sont des descendants directs (c'est-à-dire desenfants uniquement) de la catégorieidentifiéepar sonidentifiant. Celane fonctionne PAS comme leparamètre 'child_of'. Iln'y apas de valeurpar défautpour ceparamètre. [En 2.8.4]
enfant_de (entier)
Affichertoutes les catégories qui sont des descendants (c'est-à-dire lesenfantset petits-enfants) de la catégorieidentifiéepar sonidentifiant. Iln'y apas de valeurpar défautpour ceparamètre. Si leparamètreest utilisé,leparamètre hide_emptyest défini surfalse.
Unefois que vous les avez,utilisez
wp_list_pluck
pour obtenir le catID,les champs denom ou de slug dutableau de catégories renvoyé. Cetableau sera utilisépour vérifier si un article appartient à l'une de ces catégories. Vouspouvez utiliserhas_category
ouin_category
Voici comment vouspouvez étendre votre codepour vous assurer que les articles appartenant à la catégorieparente ou à ses descendants utilisent lemodèle donné
add_filter( 'single_template', function ( $single_template ) { $parent = '21'; //Change to your category ID $categories = get_categories( 'child_of=' . $parent ); $cat_names = wp_list_pluck( $categories, 'name' ); if ( has_category( 'movies' ) || has_category( $cat_names ) ) { $single_template = dirname( __FILE__ ) . '/single-movies.php'; } return $single_template; }, PHP_INT_MAX, 2 );
From my comment to the OP
My opinion, use what you are comfortable with. If there are any performance difference it will be minute/irrelevant. My preference, use the filter
To come to your real concern/question, in my opinion, the best approach will be to use the parent category ID and work from there. It will be the least resource intensive to work from here. Reverse engineering can become quite an unnecessary waste of resources.
Make use of
get_categories
to get the child categories from the given category. You can make use of either one of two parameters, eitherparent
orchild_of
parent (integer)
Display only categories that are direct descendants (i.e. children only) of the category identified by its ID. This does NOT work like the 'child_of' parameter. There is no default for this parameter. [In 2.8.4]
child_of (integer)
Display all categories that are descendants (i.e. children & grandchildren) of the category identified by its ID. There is no default for this parameter. If the parameter is used, the hide_empty parameter is set to false.
Once you have these, use
wp_list_pluck
to get the catID, name or slug fields from the returned array of categories. This array will be used to check if a post belongs to one of these categories. You can either usehas_category
orin_category
This is how you can extend your code to make sure that posts belonging to either the parent category or its descendants uses the given template
add_filter( 'single_template', function ( $single_template ) { $parent = '21'; //Change to your category ID $categories = get_categories( 'child_of=' . $parent ); $cat_names = wp_list_pluck( $categories, 'name' ); if ( has_category( 'movies' ) || has_category( $cat_names ) ) { $single_template = dirname( __FILE__ ) . '/single-movies.php'; } return $single_template; }, PHP_INT_MAX, 2 );
-
Des commentaires à ce sujet?Il serait apprécié (et debonnesmanières) si vouspouviez laisser des commentaires sur vos questions ** ouvertes **.Celane profiteraitpas seulement à vous,mais aux autres utilisateurs detrouver vos questions via lesmoteurs de recherche.Le simplefait d'abandonner vos questions comme vous l'avezfaitpourrait amener d'autres utilisateurs àignorer vos questions à l'avenir.Veuilleznous aider (et ** vous-même **) àgarder ce siteet vos questions constructifs.Merci de votre compréhension :-)Any feedback on this? It would be appreciated (and good manners) if you can leave feedback to your **open** questions. It would not only benefit you, but the other users finding your questions via search engines. Simply abandoning your questions as you did might lead to other users ignoring your questions in future. Please help us (and **yourself**) to keep this site and your questions constructive. Thanks for understanding :-)
- 1
- 2015-04-14
- Pieter Goosen
-
Fonctionne correctementpourmoi.Merci!Works correct to me. Thanks!
- 0
- 2020-08-08
- FladeX
-
- 2014-12-01
étape 1: Créez ou copiez content-single.phpet créez unnouveaufichier.parexemple: content-yourCategory.php étape 2: Ouvrez single.phpet remplacez ce
get_template_part('content','single');
par le code suivantif(is_category('yourCategory')){ get_template_part('content','yourCategory'); }else{ get_template_part('content','single.php'); }
Leparamètrepeut être un ID de catégorie,untitre de catégorie,un slug de catégorie ou untableau d'ID,denomset de slugs.
step 1: Create or copy content-single.php and create a new file. eg: content-yourCategory.php step 2: Open single.php and replace this
get_template_part('content','single');
by the following codeif(is_category('yourCategory')){ get_template_part('content','yourCategory'); }else{ get_template_part('content','single.php'); }
The parameter can be Category ID, Category Title, Category Slug or Array of IDs, names, and slugs.
-
`in_category ()` *`in_category()` *
- 4
- 2016-04-19
- Avishay28
-
- 2017-08-18
C'est unmoyenpratique de lefaire. ici collez ce code dans votre
function.php
// Custom single template by category // https://halgatewood.com/wordpress-custom-single-templates-by-category add_filter('single_template', 'check_for_category_single_template'); function check_for_category_single_template( $t ) { foreach( (array) get_the_category() as $cat ) { if ( file_exists(STYLESHEETPATH . "/single-category-{$cat->slug}.php") ) return STYLESHEETPATH . "/single-category-{$cat->slug}.php"; if($cat->parent) { $cat = get_the_category_by_ID( $cat->parent ); if ( file_exists(STYLESHEETPATH . "/single-category-{$cat->slug}.php") ) return STYLESHEETPATH . "/single-category-{$cat->slug}.php"; } } return $t; }
pourplus d'informations,consultez https://halgatewood.com/wordpress-modèles-uniques-personnalisés-par-catégorie
This is a convenient way of doing that, found here past this code into your
function.php
// Custom single template by category // https://halgatewood.com/wordpress-custom-single-templates-by-category add_filter('single_template', 'check_for_category_single_template'); function check_for_category_single_template( $t ) { foreach( (array) get_the_category() as $cat ) { if ( file_exists(STYLESHEETPATH . "/single-category-{$cat->slug}.php") ) return STYLESHEETPATH . "/single-category-{$cat->slug}.php"; if($cat->parent) { $cat = get_the_category_by_ID( $cat->parent ); if ( file_exists(STYLESHEETPATH . "/single-category-{$cat->slug}.php") ) return STYLESHEETPATH . "/single-category-{$cat->slug}.php"; } } return $t; }
for more info check out https://halgatewood.com/wordpress-custom-single-templates-by-category
-
- 2019-09-24
function get_custom_cat_template($single_template) { global $post; if ( in_category( 'category-name' )) { $single_template = dirname( __FILE__ ) . '/single-template.php'; } return $single_template; } add_filter( "single_template", "get_custom_cat_template" ) ;
function get_custom_cat_template($single_template) { global $post; if ( in_category( 'category-name' )) { $single_template = dirname( __FILE__ ) . '/single-template.php'; } return $single_template; } add_filter( "single_template", "get_custom_cat_template" ) ;
Quelleest lameilleurefaçon (performanceset structure de code) de créer unmodèlepersonnalisépour un article WordPress,qui appartient à une catégorie spécifique? J'ai réalisé que vousne pouvezpas simplement créer
single-catname.php
.Jusqu'àprésent,j'aiessayé deuxfaçons demodifier lemodèle. Mais lequel (ou un autre)est lemeilleur?
MODIFIER:
Uneidée commentincluretoutes les catégories sous/parentet ainsi de suite? J'ai réaliséen cemoment qu'ilne montrait que la catégorieprincipale ...
1. Ajouté àfunctions.php
2. Placez le code suivant dans single.php (au lieu detout autre code)et créez un
single-template.php
(avec le code du single .php) & amp; uncustom single-movies.php