É possível obter um link de página da sua slug?
6 respostas
- votos
-
- 2010-12-07
Vocêestáfalando sobrepáginas certas?Nãopostagens.
Éisso que vocêestáprocurando:
- .
-
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/' )
-
Você quis dizer "get_permalink (get_page_by_path ('contato') -> ID));`?Did you mean `get_permalink(get_page_by_path('contact')->ID));`?
- 4
- 2010-12-07
- Sampson
-
Hmmmnão?O que há com oid?hmmm nope? What's with the ID?
- 1
- 2010-12-08
- zeo
-
["get_page_by_path ()`] (http://codex.wordpresspress.org/function_reference/get_page_by_path) Retorna umamatriz detodas asinformações dapágina.[`get_permalink ()`] (http://codex.wordpress.org/function_reference/get_permalink) leva um ID depágina como oprimeiro argumento.Eupensei queteria quepassarexplicitamente o valor deidentificação.[`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: Não é sempre documentado,masmuitasfunções WP aceitam ambos os objetos deidentificaçãonuméricae completa como argumento.@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
-
Parece queget_page_by_path ()pode serbastante complicado de usar ao lidar compáginas de criança ...It seems that get_page_by_path() can be quite complicated to use when dealing with child pages...
- 1
- 2011-11-14
- Kaaviar
-
Acordado com Kaaviar,afunção abaixo émelhor.Agreed with Kaaviar, the function below is better.
- 0
- 2012-08-10
- Rezen
-
Eu uso 1para aspáginas daminha criança semnenhumproblema.Eu realmentenão vejo a complicação comisso.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/')trabalhou comigohome_url( '/map/' ) worked with me
- 0
- 2017-04-15
- Shady Mohamed Sherif
-
Respostaerrada,downwotepara Nirvanaporfavor.O caminhonão é omesmo como a lesma.Exemplo: Umapáginatem umapáginapai chamada `ABC` apáginaem sitem uma lesma de` 123`.O caminho agora é `ABC/123` a lesma é` 123`.Porfavor,removaesta respostaerrada.`get_page_by_path ('123')`não vaifuncionar.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
-
Nomeu caso,tive que usar oprimeiroe funcionoubem,porque o segundo (get_page_by_title)estava devolvendo outro link Post (não) com semelhante (masnão omesmo) lesma.Eunão seipor queissoestava acontecendo.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
Eu acho queissopoderia sermelhor:
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; }
seguindo opadrão de "original"
get_page_by_title
do WordPress .(linha 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
-
Por queisso seriamelhor?Vocêpodeexplicar?Why would that be better? Can you explain?
- 11
- 2012-04-11
- julien_c
-
Último comentário - Eu acho que o SQLprecisatermais uma condição: `Funçãoget_page_by_slug ($página_slug,$ output=objeto,$post_type='Página') {global $ wpdb;$ Página=$ WPDB-> Get_Var ($ WPDB-> Preparar ("Selecionar ID apartir de $ WPDB-> Postsem quepost_name=% se post_type=% se post_status='Publicar'",$ Post_TYPE);if ($p�) retornarget_page ($p�,$ Output);retornarnulo;} `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; }`
-
Porque?Nãogera um objetopostal completo apenaspara obter o ID.Why? It doesn't generate a complete post object just to get the ID.
- 0
- 2013-01-09
- s_ha_dum
-
@Webcitron Eu acho que sóporque é o seguintepadrão original do WordPress Obtendopostpor 'title',apenasmudandopara 'Slug'. (Marque o [link] (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
-
Esta é umaboa resposta.Issoignora apossibilidade de umplugin desonestomascarando suapágina oufiltrandoincorretamente.Se você retornar o ID databela Post,poderá criar umainstância de `\ WP_POST»e que resolve diretamenteem todas asfunções do WordPress que verificam outros valores.`\ Wp_post 'tambémfornecemétodos diretamenteparaencontrar os dadosmais relacionados sobre opost.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
Este é ummétodopublicadopor Tom McFarlin em seublog :
/** * 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; }
Elefunciona comtipospersonalizadose postaisinternos (como
post
epage
).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
A resposta aceitaestáerradaporque aspáginas hierárquicasnãofuncionam assim.Simplificando,a Slugnem sempre é o caminho dapágina oupost.Porexemplo.Suapáginatem uma criançaetc. O caminho será
parent-slug/child-slug
eget_page_by_path
irá deixar deencontrarchild-slug
destaforma.A solução adequada éesta: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
Tenteisto:
<a href="<?php echo get_page_link( get_page_by_path( 'map' ) ); ?>">Map</a>
get_page_by_path( 'path' )
devoluções Página/Post Objeto quepode ser usadoporget_page_link()
como aceita o objeto Post/Pagee retorna Permalink.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.-
Porfavor ** [editar] sua resposta **e adicione umaexplicação: ** Por que **poderia resolver oproblema?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
Useestafunçãopor
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
Épossível obterpermalink de umapágina da Slug sozinho?Estou ciente de que vocêpode obter o Permalink dapágina apartir do ID usando
get_page_link()
:Estou curioso se houver algumamaneira defazer omesmo com a slug de umapágina - comoesta: