Comment obtenir un identifiant de publication (page ou CPT) à partir d'un titre ou d'un slug?
-
-
Comment utilisiez-vous `get_page_by_title`et letype depublicationpersonnaliséest-il hiérarchique,je nepensepas que`get_page` (appelépar `get_page_by_title`)fonctionnerapour lestypesnon hiérarchiques.How were you using `get_page_by_title` and is the custom post type hierarchal, i don't think `get_page`(called by `get_page_by_title`) will work for non-hierarchal types.
- 0
- 2011-03-06
- t31os
-
Oui,letype depublicationpersonnaliséen questionn'estpas hiérarchique.Yes, the custom post type in question is non-hierachal.
- 0
- 2011-03-06
- jnthnclrk
-
Ignorez le commentaireprécédent concernant lefait d'être hiérarchique,celane devraitpas avoir d'importance,comment appeliez-vous `get_page_by_title`?Ignore previous comment regarding being hierarchal, that shouldn't matter, how were you calling `get_page_by_title`?
- 0
- 2011-03-06
- t31os
-
5 réponses
- votes
-
- 2011-03-06
vouspouvez utiliser cettefonction qui sautepargoogle "obtenir l'articlepartitre"
/** * Retrieve a post given its title. * * @uses $wpdb * * @param string $post_title Page title * @param string $post_type post type ('post','page','any custom type') * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. * @return mixed */ function get_post_by_title($page_title, $post_type ='post' , $output = OBJECT) { global $wpdb; $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type)); if ( $post ) return get_post($post, $output); return null; }
you can use this function that jumps by google "get post by title"
/** * Retrieve a post given its title. * * @uses $wpdb * * @param string $post_title Page title * @param string $post_type post type ('post','page','any custom type') * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. * @return mixed */ function get_post_by_title($page_title, $post_type ='post' , $output = OBJECT) { global $wpdb; $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type)); if ( $post ) return get_post($post, $output); return null; }
-
Jusqu'àprésent,j'ai réussi à éviter d'utiliser les requêtes DB,carje préfère utiliser lesfonctions WP standard.Est-ce vraiment le seulmoyen de réaliser ce dontj'aibesoin?So far I've managed to avoid using DB queries, as I prefer to use standard WP functions. Is this really the only way to achieve what I need?
- 1
- 2011-03-06
- jnthnclrk
-
Le codepubliéest àpeuprès une copie directe de la [fonction] «get_page_by_title» (http://core.trac.wordpress.org/browser/tags/3.1/wp-includes/post.php#L3162),la différencemajeurevoici que celafonctionnerapour lestypesnon hiérarchiques,donc cela vaut lapeine d'avoir dans votre collection defonctions.The code posted is pretty much a direct copy of the `get_page_by_title` [function](http://core.trac.wordpress.org/browser/tags/3.1/wp-includes/post.php#L3162), the major difference here is that it'll work for non-hierarchal types, so it's one worth having in your function collection.
- 0
- 2011-03-06
- t31os
-
@t31os Jen'aijamais dit que c'était lemien,j'ai seulement ajouté lepaean $post_typeet oui,il va dansma collection.@t31os I never said it was mine i only added the $post_type paean to it and yep its going to my collection.
- 0
- 2011-03-06
- Bainternet
-
Jene t'accusais de rienmonpote,si quelque choseje soutiensta réponse ..;) Tu as déjàmon +1 .. :)I wasn't accusing you of anything mate, if anything i'm supporting your answer.. ;) You already got my +1.. :)
- 0
- 2011-03-06
- t31os
-
@t31osje sais,c'estjuste unemauvaiseblague :)@t31os I know ,its just a bad joke :)
- 0
- 2011-03-06
- Bainternet
-
En quoiest-ce différent de `get_page_by_title ()`natif? .. `get_page ()`est àpeuprès un alias de `get_post ()` Jene voispas comment le changement a unimpact sur quoi que ce soit.How is this different from native `get_page_by_title()`?.. `get_page()` is pretty much alias of `get_post()` I don't see how change impact anything.
- 0
- 2011-03-06
- Rarst
-
@Rarst Maintenant que vous avez souligné que c'est lamême chose,je ne voispas la différence.@Rarst Now that you pointed that out it is the same, i can't see the difference.
- 0
- 2011-03-06
- Bainternet
-
@t31os alors où la chose _non-hiérarchique_ que vous avezmentionnéeentreen jeu si lafonctionestessentiellement lamême? ..@t31os so where does _non-hierarchical_ thing you mentioned comes into play if function is essentially same?..
- 0
- 2011-03-06
- Rarst
-
Jene saispas à quoije pensais cematin,get_page appelle quandmêmeget_post,et jen'ai aucuneidée depourquoije pensais queget_pagene fonctionnait quepour lestypes hiérarchiques,je nepensepas que ce soit vraien l'état.Don't know what i was thinking this morning, get_page calls get_post anyway, and i have no clue why i thought get_page only works for hierarchal types, i don't think that's true as it happens.
- 0
- 2011-03-06
- t31os
-
Celapeut êtrefaitfacilement avec l'objetpage.Voirma réponse ci-dessous.This can be done easily with the page object. See my answer below.
- 0
- 2017-07-29
- Phill Healey
-
- 2011-06-17
Il vousmanque unparamètre defonction.Jetez unnullpour le deuxièmeparamètrefacultatif $ outputet cettefonction devraitfonctionnerpour vous.
get_page_by_title('My post title', null, 'customposttype');
Je viens de rencontrer lemêmeproblèmeet l'ajout de la valeurnull l'a corrigépourmoi.
You are missing a function parameter. Throw a null in for the second optional paramter $output and this function should work for you.
get_page_by_title('My post title', null, 'customposttype');
I just ran into the same issue and adding the null fixed it for me.
-
Ce «null» devrait vraiment être «OBJECT»pourplus de clarté.Mais,oui,iljetaitessentiellement letype depublication commetype de sortieen omettant letype de sortie.That `null` should really be `OBJECT` for clarity. But, yes he was essentially throwing the post type in as the output type by leaving out the output type.
- 0
- 2017-07-29
- Phill Healey
-
- 2011-06-17
J'aitendance à éviter les requêtes directes debase de données.À laplace,j'utilise l'objet
WP_Query
pour analyser les choses àmaplace.Il s'agit,en gros,d'unefonction quej'utilise dans l'un demesthèmespour obtenir un articlebasé sur un slug donné:
function get_post_id( $slug, $post_type ) { $query = new WP_Query( array( 'name' => $slug, 'post_type' => $post_type ) ); $query->the_post(); return get_the_ID(); }
Cela créera une requête utilisant l'API WPpour récupérer unepublication d'untype spécifique avec un slug donné,exécutera lesfonctions deboucle régulières sur le résultatet retournera l'ID de lapublication.Vouspouvez également l'utiliserpour renvoyer l'intégralité dumessageen modifiant unpeu lafonction,mais c'est à vous de décider.
I tend to shy away from direct DB queries. Instead, I use the
WP_Query
object to parse things for me.This is, basically, a function I use in one of my themes to get a post based on a given slug:
function get_post_id( $slug, $post_type ) { $query = new WP_Query( array( 'name' => $slug, 'post_type' => $post_type ) ); $query->the_post(); return get_the_ID(); }
This will create a query using the WP API to fetch a post of a specific type with a given slug, will run the regular loop functions on the result, and return the ID of the post. You could also use it to return the entire post by modifying the function a bit, but that's up to you.
-
Au lieu de `$ query->the_post ()` quimodifie laboucleet perturberatoutes lesfonctions `get_the_xxx` aprèselle,utilisezplutôt: if ($ query-> have_posts ()) { return $ query->posts [0] -> ID; } autre { return 0; }Instead of `$query->the_post()` which alters the loop and will disrupt any `get_the_xxx` functions after it, rather use: if ($query->have_posts()) { return $query->posts[0]->ID; } else { return 0; }
- 0
- 2015-12-14
- Mikepote
-
- 2017-07-29
Cela datemaintenant de quelques années,mais cela apparaîttoujours lors de la recherche sur Google.Alors,voici unmoyen simple de lefaire:
$page = get_page_by_title( 'my post title' );
ou
$page = get_post_ID_by_title('my post title', OBJECT, 'customposttype');
Ensuite,utilisez simplement l'objet $pagepour récupérer l'ID:
$page->ID
This is a few years old now, but it still pops up when searching for this on Google. So, here's a simple way to do it:
$page = get_page_by_title( 'my post title' );
or
$page = get_post_ID_by_title('my post title', OBJECT, 'customposttype');
Then just use the $page object to grab the ID:
$page->ID
-
- 2018-02-03
Actuellement (WP> 4.9.2),voustrouverez votre "tout" article/page donné,etc.partitre/slug de cettefaçon:
$page = get_posts( array( //'name' => 'your-post-slug', // by post slug 'title' => 'Your post title', // by post title 'post_type' => 'page' // post type of your preference ) ); if ($page = $page[0]) // First/lowest ID taken if many objects { // Then you do whatever is needed... // $id = $page->id; // $content = $page->post_content; // or $content = apply_filters('the_content', $page->post_content); // etc. }
Currently (WP >4.9.2) you'll find your "any" given post/page etc. by title/slug this way:
$page = get_posts( array( //'name' => 'your-post-slug', // by post slug 'title' => 'Your post title', // by post title 'post_type' => 'page' // post type of your preference ) ); if ($page = $page[0]) // First/lowest ID taken if many objects { // Then you do whatever is needed... // $id = $page->id; // $content = $page->post_content; // or $content = apply_filters('the_content', $page->post_content); // etc. }
J'aiparcouru le Codex,je n'aipas réussi àfairefonctionnerget_page_by_title ()et je suis assez surpris qu'ilne semblepas y avoir defonction WP standardpour cettetâche.
J'aibesoin d'obtenir l'ID detout article/cpt oupage donnéen utilisant soit le slug dutitre de l'article/de lapage.Idéalement,je recherche les éléments suivants:
get_post_ID_by_title('My post title', 'customposttype');
Que dois-jefaire?