Obtenir l'identifiant de la page par modèle
4 réponses
- votes
-
- 2014-11-02
Lorsqu'unepageest créée,lemodèle attribué à cettepageestenregistréen tant queméta depublicationpersonnalisée de lamêmemanière que les champspersonnalisés. La
meta_key
est_wp_page_template
et lameta_value
sera lemodèle depageVouspouvez simplement utiliser
get_pages
pour récupérertoutes lespages qui ont unemeta_value
dumodèle spécifié$pages=get_pages (tableau ( 'meta_key'=> '_wp_page_template', 'meta_value'=> 'page-special.php' )); foreach ($pages as $page) { echo $page- > ID. '& lt;br/>'; }
MODIFIER 23-07-2015
Si vous avezjustebesoin desidentifiants depage,vous utilisez
get_posts
puispassez simplementpage
commepost_type
et 'idscomme valeur des champs
. Celagarantira une requêtebeaucoupplus rapideet beaucoupplus optimisée carnousne retournerons que la colonnepostid dans labase de donnéeset pastoutespour lespages données.( Nécessite PHP 5.4+ )
$ args=[ 'post_type'=> 'page', 'champs'=> 'ids', 'nopaging'=> vrai, 'meta_key'=> '_wp_page_template', 'meta_value'=> 'page-special.php' ]; $pages=get_posts ($ args); foreach ($pages comme $page) echo $page. '& lt;/br >';
When a page is created, the assigned template to that page is saved as custom post meta in the same way as custom fields. The
meta_key
is_wp_page_template
and themeta_value
will be the page templateYou can simply make use of
get_pages
to retrieve all pages which have ameta_value
of the specified template$pages = get_pages(array( 'meta_key' => '_wp_page_template', 'meta_value' => 'page-special.php' )); foreach($pages as $page){ echo $page->ID.'<br />'; }
EDIT 23-07-2015
If one just needs the page ids, then you make use of
get_posts
and then just passpage
aspost_type
and 'idsas
fields` value. This will ensure a much faster, much more optimized query as we will only return the post id column in the db and not all of them for the given pages(Requires PHP 5.4+)
$args = [ 'post_type' => 'page', 'fields' => 'ids', 'nopaging' => true, 'meta_key' => '_wp_page_template', 'meta_value' => 'page-special.php' ]; $pages = get_posts( $args ); foreach ( $pages as $page ) echo $page . '</br>';
-
Hey,merci.N'est-cepas unpeutrop "lourd"?(parcouranttoutes lespages)Hey, Thanks. Isn't a bit too "heavy"? (running through all the pages)
- 0
- 2014-11-02
- user3800799
-
Dépend dunombre depages que vous avez.Iln'y aen faitpas demoyennatifplus rapide queje connaissepour récupérer ces données.Si vous avezbeaucoup depages,je vous suggère d'utiliser destransitoirespour stocker ces donnéeset de vider/supprimer uniquement letransitoire lorsqu'unenouvellepageestpubliéeDepends on how many pages you have. There is actually no faster native way that I know of to retrieve this data. If you have a lot of pages, I would suggest that you make use of transients to store that data and only flush/delete the transient when a new page is published
- 0
- 2014-11-02
- Pieter Goosen
-
Monplaisir,heureux depouvoir aider.Prendreplaisir :-)My pleasure, glad I could help. Enjoy :-)
- 0
- 2014-11-02
- Pieter Goosen
-
@ user3800799 J'aimis àjour lemessage si vous souhaitez uniquement obtenir lesidentifiants,rien d'autre@user3800799 I have updated the post if you are only interested in getting the ids, nothing else
- 0
- 2015-07-23
- Pieter Goosen
-
Vouspouvez également utiliser `set_transient` (https://codex.wordpress.org/Transients_API) si vousne voulezpastropinterroger labase de données.You could also use `set_transient` (https://codex.wordpress.org/Transients_API) if you don't want to query the database too much.
- 0
- 2016-05-19
- Chris Andersson
-
@ChrisAndersson Àmoins que vousn'ayez des centaines depages,définir untransitoire sera assezinutileici.Mon coden'effectue qu'une seule requête debase de données ultra-rapide,carnousne demandons que les ID depublication,ce qui augmente considérablement lesperformances.Lestransitoireseffectuent deux appels debase de données à chaque chargement depage,bien que celapuisse être unpeuplus rapide.Lestransitoiresne sont utiles que sur des opérations coûteuses@ChrisAndersson Unless you have hundreds of pages, setting a transient will be pretty useless here. My code perform only one superfast db query as we only query post ID's which dramatically increase performance. Transients perform two db calls every page load, although it might be a tad faster. Transients are only useful on expensive operations
- 0
- 2016-05-19
- Pieter Goosen
-
Merci,c'estexactement ce queje cherchais :).J'ai unmodèle deblog quej'inclus dansmonthème ... c'esttrès utilepour obtenir l'identifiant de lapage attribué aumodèle deblog,plutôt que d'avoir à le saisirmanuellement à chaquefois!Thank you, this is exactly what I was looking for :). I have a blog template that I include in my theme...it's very useful to get the page id of the page assigned to the blog template, rather than having to manually input it every time!
- 0
- 2019-07-15
- Jordan Carter
-
- 2018-02-06
Si votremodèle depage réside dans un sous-dossier,dossier-thème/page-templates/page-template.php,la requête ci-dessousfonctionnera:
$page_details = get_pages( array( 'post_type' => 'page', 'meta_key' => '_wp_page_template', 'hierarchical' => 0, 'meta_value' => 'page-templates/page-template.php' ));
Les codes ci-dessus affichent également des sous-pages.
Merci
If your page template resides inside sub-folder, theme-folder/page-templates/page-template.php then you below query will works:
$page_details = get_pages( array( 'post_type' => 'page', 'meta_key' => '_wp_page_template', 'hierarchical' => 0, 'meta_value' => 'page-templates/page-template.php' ));
This above codes also display sub-pages as well.
Thanks
-
- 2018-08-20
Ce qui suitest un script légèrementplus articulé quiprenden compte une langue,sinécessaire. Notez qu'il suppose l'utilisation de Polylang,pas de WPML.
function get_post_id_by_template($template,$lang_slug = null){ global $wpdb; $wh = ($lang_slug) ? " AND t.slug = %s" : ""; $query = $wpdb->prepare( "SELECT DISTINCT p.ID FROM $wpdb->posts p INNER JOIN $wpdb->postmeta meta ON meta.post_id = p.ID INNER JOIN $wpdb->term_relationships tr ON meta.post_id = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN $wpdb->terms t ON tt.term_id = t.term_id WHERE p.post_status = 'publish' AND meta.meta_key = %s AND meta.meta_value = %s" . $wh, '_wp_page_template', $template, $lang_slug ); $ids = $wpdb->get_results($query); if($ids && isset($ids[0])){ $p = $ids[0]; return $p->ID; } else { return false; } }// get_post_id_by_template
The following is a slightly more articulated script that take into account a language, if needed. NOTE that it assumes the usage of Polylang, not WPML.
function get_post_id_by_template($template,$lang_slug = null){ global $wpdb; $wh = ($lang_slug) ? " AND t.slug = %s" : ""; $query = $wpdb->prepare( "SELECT DISTINCT p.ID FROM $wpdb->posts p INNER JOIN $wpdb->postmeta meta ON meta.post_id = p.ID INNER JOIN $wpdb->term_relationships tr ON meta.post_id = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN $wpdb->terms t ON tt.term_id = t.term_id WHERE p.post_status = 'publish' AND meta.meta_key = %s AND meta.meta_value = %s" . $wh, '_wp_page_template', $template, $lang_slug ); $ids = $wpdb->get_results($query); if($ids && isset($ids[0])){ $p = $ids[0]; return $p->ID; } else { return false; } }// get_post_id_by_template
-
- 2019-11-12
Voici unefonction complète quifonctionne avec WPMLet Polylang. Crédit à https://github.com/cyrale/
/** * Search for a page with a particular template. * * @param string $template Template filename. * @param array $args (Optional) See also get_posts() for example parameter usage. * @param bool $single (Optional) Whether to return a single value. * * @return Will be an array of WP_Post if $single is false. Will be a WP_Post object if the page is find, FALSE otherwise */ if (!function_exists('get_page_by_template')) { function get_page_by_template($template, $args = array(), $single = true) { $pages_by_template = wp_cache_get('pages_by_template', 'cyrale'); if (empty($pages_by_template) || !is_array($pages_by_template)) { $pages_by_template = array(); } if (!isset($pages_by_template[$template])) { $args = wp_parse_args(array( 'posts_per_page' => -1, 'post_type' => 'page', 'suppress_filters' => 0, 'meta_query' => array( array( 'key' => '_wp_page_template', 'value' => $template, ), ), ), $args); $pages = get_posts($args); $pages_by_template[$template]= array( 'single' => !empty($pages) && is_array($pages) ? reset($pages) : false, 'pages' => $pages, ); } wp_cache_set('pages_by_template', $pages_by_template, 'cyrale'); return $pages_by_template[$template][$single ? 'single' : 'pages']; } }
Here is a complete function that works with WPML and Polylang. Credit to https://github.com/cyrale/
/** * Search for a page with a particular template. * * @param string $template Template filename. * @param array $args (Optional) See also get_posts() for example parameter usage. * @param bool $single (Optional) Whether to return a single value. * * @return Will be an array of WP_Post if $single is false. Will be a WP_Post object if the page is find, FALSE otherwise */ if (!function_exists('get_page_by_template')) { function get_page_by_template($template, $args = array(), $single = true) { $pages_by_template = wp_cache_get('pages_by_template', 'cyrale'); if (empty($pages_by_template) || !is_array($pages_by_template)) { $pages_by_template = array(); } if (!isset($pages_by_template[$template])) { $args = wp_parse_args(array( 'posts_per_page' => -1, 'post_type' => 'page', 'suppress_filters' => 0, 'meta_query' => array( array( 'key' => '_wp_page_template', 'value' => $template, ), ), ), $args); $pages = get_posts($args); $pages_by_template[$template]= array( 'single' => !empty($pages) && is_array($pages) ? reset($pages) : false, 'pages' => $pages, ); } wp_cache_set('pages_by_template', $pages_by_template, 'cyrale'); return $pages_by_template[$template][$single ? 'single' : 'pages']; } }
Je veux savoir s'ilestpossible d'obtenir l'ID d'unepage avec unmodèle spécifique.Est-cepossible d'obtenir l'ID d'unepage attribuée à "page-special.php"?