Est-il possible d'obtenir un lien de page à partir de son slug?
6 réponses
- votes
-
- 2010-12-07
Vousparlez de Pages,n'est-cepas?Pas demessages.
Est-ce ce que vous recherchez:
-
get_permalink( get_page_by_path( 'map' ) )
-
get_permalink( get_page_by_title( 'Map' ) )
-
home_url( '/map/' )
You're talking about Pages right? Not Posts.
Is this what you looking for:
get_permalink( get_page_by_path( 'map' ) )
get_permalink( get_page_by_title( 'Map' ) )
home_url( '/map/' )
-
Vouliez-vous dire `get_permalink (get_page_by_path ('contact') -> ID));`?Did you mean `get_permalink(get_page_by_path('contact')->ID));`?
- 4
- 2010-12-07
- Sampson
-
hmmmnon?Qu'est-ce que l'ID?hmmm nope? What's with the ID?
- 1
- 2010-12-08
- zeo
-
[`get_page_by_path ()`] (http://codex.wordpress.org/Function_Reference/get_page_by_path) renvoie untableau detoutes lesinformations de lapage.[`get_permalink ()`] (http://codex.wordpress.org/Function_Reference/get_permalink)prend un ID depage commepremier argument.Jepensais queje devraisexplicitementtransmettre la valeur de l'ID.[`get_page_by_path()`](http://codex.wordpress.org/Function_Reference/get_page_by_path) returns an array of all page information. [`get_permalink()`](http://codex.wordpress.org/Function_Reference/get_permalink) takes a page ID as the first argument. I thought I'd have to explicitly pass the ID value.
- 3
- 2010-12-08
- Sampson
-
@Jonathan: Cen'estpastoujours documenté,mais denombreusesfonctions WP acceptent à lafois les IDnumériqueset les objets depublication complets comme argument.@Jonathan: It's not always documented, but many WP functions accept both numeric ID's and full post objects as the argument.
- 10
- 2010-12-08
- Jan Fabry
-
Il semble queget_page_by_path ()puisse être assez compliqué à utiliser lorsqu'il s'agit depagesenfants ...It seems that get_page_by_path() can be quite complicated to use when dealing with child pages...
- 1
- 2011-11-14
- Kaaviar
-
D'accord avec Kaaviar,lafonction ci-dessousestmeilleure.Agreed with Kaaviar, the function below is better.
- 0
- 2012-08-10
- Rezen
-
J'utilise 1pourmespagesenfant sansproblème.Jene vois vraimentpas la complication avec cela.I use 1 for my child pages with no issue. I really don't see the complication with it.
- 0
- 2014-12-19
- Jeremy
-
home_url ('/map/') atravaillé avecmoihome_url( '/map/' ) worked with me
- 0
- 2017-04-15
- Shady Mohamed Sherif
-
mauvaise réponse,voter contre lenirvana s'il vousplaît.Le cheminn'estpas lemême que celui de la limace.Exemple: unepage a unepageparent appelée `abc` lapageelle-même a un slug de` 123`.Le cheminestmaintenant `abc/123` le slugest` 123`.Veuillez supprimer cettemauvaise réponse.`get_page_by_path ('123')`ne fonctionnerapas.wrong answer, downvote to nirvana please. The path is not the same like the slug. Example: a page has a parent page called `abc` the page itself has a slug of `123`. The path now is `abc/123` the slug is `123`. Please remove this wrong answer. `get_page_by_path( '123' )` wont work.
- 1
- 2017-09-01
- Toskan
-
Dansmon cas,j'ai dû utiliser lepremieret cela abien fonctionné,car le second (get_page_by_title) renvoyait un autre lien depublication (pas depage) avec un slug similaire (maispas lemême).Jene saispaspourquoi cela sepassait.In my case I had to use the first one and it worked fine, because the second one (get_page_by_title) was returning another post (not page) link with similar (but not the same) slug. I don't know why this was happening.
- 1
- 2019-06-10
- Adriana Hernández
-
- 2011-02-28
Jepense que celapourrait êtremieux:
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) { global $wpdb; $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, $post_type ) ); if ( $page ) return get_page($page, $output); return null; }
suivant lemodèle de
get_page_by_title
de wordpress .(ligne 3173)rgds
I think this could be better:
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) { global $wpdb; $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, $post_type ) ); if ( $page ) return get_page($page, $output); return null; }
following the pattern of "original"
get_page_by_title
of wordpress. (line 3173)rgds
-
Pourquoi serait-cemieux?Peux-tuexpliquer?Why would that be better? Can you explain?
- 11
- 2012-04-11
- julien_c
-
Dernier commentaire - Jepense que sql doit avoir une condition supplémentaire: `functionget_page_by_slug ($page_slug,$ output=OBJECT,$post_type='page') {global $ wpdb;$page=$ wpdb->get_var ($ wpdb->prepare ("SELECT ID FROM $ wpdb->posts WHEREpost_name=% s ANDpost_type=% s ANDpost_status='publish'",$page_slug,$post_type));if ($page) returnget_page ($page,$ sortie);returnnull;} `Last comment - I think that sql needs to have one more condition: `function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) { global $wpdb; $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s AND post_status = 'publish'", $page_slug, $post_type ) ); if ( $page ) return get_page($page, $output); return null; }`
-
Pourquoi?Ilne génèrepas d'objet depublication complet uniquementpour obtenir l'ID.Why? It doesn't generate a complete post object just to get the ID.
- 0
- 2013-01-09
- s_ha_dum
-
@webcitron Jepensejusteparce que suit lemodèle original de Wordpressen obtenant unmessagepar «titre»,en changeant simplementpar «slug». (consultez le [lien] (http://core.trac.wordpress.org/browser/tags/3.1/wp-includes/post.php#L3173))@webcitron I think just because is following original pattern of Wordpress getting post by 'title', just changing for 'slug'. (check the [link](http://core.trac.wordpress.org/browser/tags/3.1/wp-includes/post.php#L3173))
- 0
- 2013-05-13
- Matheus Eduardo
-
C'est unebonne réponse.Cela évite lapossibilité qu'unpluginmalveillantmasque votrepage oune lafiltrepas correctement.Si vous retournez l'identifiant de latable depublication,vouspouvez créer uneinstance de `\ WP_Post` àpartir de celle-ci,et cela se résout directement danstoutes lesfonctions wordpress qui vérifient d'autres valeurs.`\ WP_Post`fournit également desméthodes directementpourtrouver laplupart des données relatives à lapublication.This is a good answer. This bypasses the possiblity of a rogue plugin masking your page or incorrectly filtering it. If you return the id from the post table, then you can create an instance of `\WP_Post` from it, and that resolves directly in all of the wordpress functions that check for other values. `\WP_Post` also provides methods directly to find most related data about the post.
- 0
- 2018-03-23
- mopsyd
-
- 2013-01-31
Il s'agit d'uneméthodepubliéepar Tom McFarlin sur sonblog :
/** * Returns the permalink for a page based on the incoming slug. * * @param string $slug The slug of the page to which we're going to link. * @return string The permalink of the page * @since 1.0 */ function wpse_4999_get_permalink_by_slug( $slug, $post_type = '' ) { // Initialize the permalink value $permalink = null; // Build the arguments for WP_Query $args = array( 'name' => $slug, 'max_num_posts' => 1 ); // If the optional argument is set, add it to the arguments array if( '' != $post_type ) { $args = array_merge( $args, array( 'post_type' => $post_type ) ); } // Run the query (and reset it) $query = new WP_Query( $args ); if( $query->have_posts() ) { $query->the_post(); $permalink = get_permalink( get_the_ID() ); wp_reset_postdata(); } return $permalink; }
Ilfonctionne avec destypes depublicationpersonnaliséset destypes depublicationintégrés (tels que
post
etpage
).This is a method published by Tom McFarlin on his blog:
/** * Returns the permalink for a page based on the incoming slug. * * @param string $slug The slug of the page to which we're going to link. * @return string The permalink of the page * @since 1.0 */ function wpse_4999_get_permalink_by_slug( $slug, $post_type = '' ) { // Initialize the permalink value $permalink = null; // Build the arguments for WP_Query $args = array( 'name' => $slug, 'max_num_posts' => 1 ); // If the optional argument is set, add it to the arguments array if( '' != $post_type ) { $args = array_merge( $args, array( 'post_type' => $post_type ) ); } // Run the query (and reset it) $query = new WP_Query( $args ); if( $query->have_posts() ) { $query->the_post(); $permalink = get_permalink( get_the_ID() ); wp_reset_postdata(); } return $permalink; }
It works with custom post types and built-in post types (such as
post
andpage
). -
- 2017-09-01
la réponse acceptéeestfausse car lespages hiérarchiquesne fonctionnentpas comme ça.Entermes simples,le slugn'estpastoujours le chemin de lapage ou de l'article.Parexemple.votrepage a unenfantetc. le chemin sera
parent-slug/child-slug
etget_page_by_path
ne parviendrapas àtrouverchild-slug
de cettefaçon.Labonne solutionest la suivante:function mycoolprefix_post_by_slug($the_slug, $post_type = "page"){ $args = array( 'name' => $the_slug, 'post_type' => $post_type, 'post_status' => 'publish', 'numberposts' => 1 ); $my_page = get_posts($args)[0]; return $my_page; } <a href="<?php echo mycoolprefix_post_by_slug('map'); ?>">Map</a>
the accepted answer is wrong because hierarchical pages don't work like that. Simply put, the slug is not always the path of the page or post. E.g. your page has a child etc. the path will be
parent-slug/child-slug
andget_page_by_path
will fail to findchild-slug
this way. The proper solution is this:function mycoolprefix_post_by_slug($the_slug, $post_type = "page"){ $args = array( 'name' => $the_slug, 'post_type' => $post_type, 'post_status' => 'publish', 'numberposts' => 1 ); $my_page = get_posts($args)[0]; return $my_page; } <a href="<?php echo mycoolprefix_post_by_slug('map'); ?>">Map</a>
-
- 2018-02-26
Essayez ceci:
<a href="<?php echo get_page_link( get_page_by_path( 'map' ) ); ?>">Map</a>
get_page_by_path( 'path' )
renvoie un objetpage/article quipeutensuite être utiliséparget_page_link()
caril accepte l'objet article/pageet renvoie unpermalien.Try This:
<a href="<?php echo get_page_link( get_page_by_path( 'map' ) ); ?>">Map</a>
get_page_by_path( 'path' )
returns page/post object which can be then used byget_page_link()
as it accepts post/page object and returns permalink.-
Veuillez ** [modifier] votre réponse **,et ajouter uneexplication: **pourquoi ** celapourrait-il résoudre leproblème?Please **[edit] your answer**, and add an explanation: **why** could that solve the problem?
- 2
- 2018-02-26
- fuxia
-
- 2014-11-11
function theme_get_permalink_by_title( $title ) { // Initialize the permalink value $permalink = null; // Try to get the page by the incoming title $page = get_page_by_title( strtolower( $title ) ); // If the page exists, then let's get its permalink if( null != $page ) { $permalink = get_permalink( $page->ID ); } // end if return $permalink; } // end theme_get_permalink_by_title
Utilisez cettefonctionpar
if( null == theme_get_permalink_by_title( 'Register For This Site' ) ) { // The permalink doesn't exist, so handle this however you best see fit. } else { // The page exists, so do what you need to do. } // end if/else
function theme_get_permalink_by_title( $title ) { // Initialize the permalink value $permalink = null; // Try to get the page by the incoming title $page = get_page_by_title( strtolower( $title ) ); // If the page exists, then let's get its permalink if( null != $page ) { $permalink = get_permalink( $page->ID ); } // end if return $permalink; } // end theme_get_permalink_by_title
Use this function by
if( null == theme_get_permalink_by_title( 'Register For This Site' ) ) { // The permalink doesn't exist, so handle this however you best see fit. } else { // The page exists, so do what you need to do. } // end if/else
Est-ilpossible d'obtenir le lienpermanent d'unepage uniquement àpartir du slug?Je sais que vouspouvez obtenir le lienpermanent de lapage àpartir de l'IDen utilisant
get_page_link()
:Je suis curieux de savoir s'ilexiste unmoyen defaire demême avec le slug d'unepage - comme ceci: