¿Es posible obtener un enlace de página desde su slug?
6 respuestas
- votos
-
- 2010-12-07
Estás hablando depáginas,¿verdad?Nopublicaciones.
¿Esesto lo quebusca?
-
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/' )
-
¿Quiso decir `get_permalink (get_page_by_path ('contact') -> ID));`?Did you mean `get_permalink(get_page_by_path('contact')->ID));`?
- 4
- 2010-12-07
- Sampson
-
hmmmnop?¿Quépasa con laidentificación?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) devuelve unamatriz detoda lainformación de lapágina.[`get_permalink ()`] (http://codex.wordpress.org/Function_Reference/get_permalink)toma una ID depágina comoprimer argumento.Pensé quetendría quepasarexplícitamenteel valor de 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: No siempreestá documentado,peromuchasfunciones de WP aceptantanto IDnuméricos como objetos depublicación completos 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 ()puede serbastante complicado de usar cuando setrata depáginas secundarias ...It seems that get_page_by_path() can be quite complicated to use when dealing with child pages...
- 1
- 2011-11-14
- Kaaviar
-
De acuerdo con Kaaviar,lafunción a continuaciónesmejor.Agreed with Kaaviar, the function below is better.
- 0
- 2012-08-10
- Rezen
-
Utilizo 1paramispáginas secundarias sinproblema.Realmenteno veo la complicación coneso.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/')trabajó conmigohome_url( '/map/' ) worked with me
- 0
- 2017-04-15
- Shady Mohamed Sherif
-
respuestaincorrecta,votonegativo alnirvana,porfavor.El caminonoeselmismo queel de lababosa.Ejemplo: unapáginatiene unapáginaprincipal llamada `abc`,lapáginaen sítiene un slug de` 123`.La ruta ahoraes `abc/123` yel sluges` 123`.Eliminaesta respuestaincorrecta.`get_page_by_path ('123')`nofuncionará.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
-
Enmi caso,tuve que usarelprimero yfuncionóbien,porqueel segundo (get_page_by_title)estaba devolviendo otroenlace depublicación (nopágina) con un slug similar (peronoelmismo).No sépor quéestabapasandoesto.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
Creo queestopodría sermejor:
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; }
siguiendoelpatrón "original"
get_page_by_title
de wordpress .(línea 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 qué seríamejor?¿Puedesexplicar?Why would that be better? Can you explain?
- 11
- 2012-04-11
- julien_c
-
Último comentario: creo que sql debetener una condiciónmás: `functionget_page_by_slug ($page_slug,$ output=OBJECT,$post_type='page') {global $ wpdb;$página=$ wpdb->get_var ($ wpdb->prepare ("SELECCIONAR ID DE $ wpdb->publicaciones DONDEpost_name=% s Ypost_type=% s ANDpost_status='publicar'",$page_slug,$post_type));if ($página) returnget_page ($página,$ salida);devolvernulo;} `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; }`
-
¿Por qué?Nogenera un objeto depublicación completo solopara obtener laidentificación.Why? It doesn't generate a complete post object just to get the ID.
- 0
- 2013-01-09
- s_ha_dum
-
@webcitron Creo que soloporque sigueelpatrón original de Wordpress recibiendopublicacionespor 'título',simplemente cambiandopor 'slug'. (consulteel [enlace] (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
-
Estaes unabuena respuesta.Estoevita laposibilidad de que un complementomaliciosoenmascare supágina o lafiltreincorrectamente.Si devuelve laidentificación de latabla depublicaciones,puede crear unainstancia de `\ WP_Post` apartir deella,yeso se resuelve directamenteen todas lasfunciones de wordpress que comprueban otros valores.`\ WP_Post`tambiénproporcionamétodos directamenteparaencontrar lamayoría de los datos relacionados con lapublicación.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
Estees unmétodopublicadopor Tom McFarlin en sublog :
/** * 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; }
Funciona contipos depublicacionespersonalizadas ytipos depublicacionesintegrados (como
post
ypage
).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 respuesta aceptadaesincorrectaporque laspáginasjerárquicasnofuncionan así.Enpocaspalabras,lababosano siemprees la ruta de lapágina opublicación.P.ej.supáginatiene un hijo,etc. la ruta será
parent-slug/child-slug
yget_page_by_path
nopodráencontrarchild-slug
deestamanera.La solución adecuadaesesta: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
Pruebeesto:
<a href="<?php echo get_page_link( get_page_by_path( 'map' ) ); ?>">Map</a>
get_page_by_path( 'path' )
devuelveel objeto depágina/publicación que luegopuede ser utilizadoporget_page_link()
ya que aceptael objeto depublicación/página y devuelveelenlacepermanente.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.-
** [edite] su respuesta ** y agregue unaexplicación: ** ¿por qué **estopodría resolverelproblema?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
Utiliceestafunción antes de
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
¿Esposible obtenerelenlacepermanente de unapágina solo desdeel slug?Soy consciente de quepuede obtenerelenlacepermanente de lapágina apartir del ID utilizando
get_page_link()
:Tengo curiosidadpor saber si hay algunaforma de hacer lomismo conel slug de unapágina,comoesta: