¿Cómo recupero el slug de la página actual?
11 respuestas
- votos
-
-
Gracias.Tu soluciónfuncionamuybien.Solonecesito hacereco de lababosa: ` Php publicación $global; $post_slug=$post->post_name;echo $post_slug; ?> `Thank you. Your solution works great. Just need to echo the slug: `post_name; echo $post_slug; ?>`
- 4
- 2012-02-13
- sarytash
-
Como dijo sarytash,necesitas "hacereco".Entonces,esto seríaideal: ` Phpglobal $post;echo $post->post_name;?> `Like sarytash said, you need to `echo` it. So, this'd be ideal: `post_name; ?>`
- 2
- 2013-10-11
- its_me
-
¿Quépasa con [`$ WP_Post`] (https://codex.wordpress.org/Class_Reference/WP_Post)?What about [`$WP_Post`](https://codex.wordpress.org/Class_Reference/WP_Post)?
- 0
- 2019-04-24
- Peter Mortensen
-
-
- 2015-05-20
Según otras respuestas,slug se almacenaen lapropiedad
post_name
.Sibien podría acceder directamente,prefiero lafunciónget_post_field()
(infrautilizada)para acceder a laspropiedades de lapublicación quenotienen una API adecuadaparaellas.Requiere que lapublicación seproporcioneexplícitamente ynoes lapredeterminadapara lapublicación actual,por lo queen sutotalidadpara lapublicación actual sería:
$slug = get_post_field( 'post_name', get_post() );
As per other answers, slug is stored in the
post_name
property. While it could be accessed directly, I prefer the (underused)get_post_field()
function for accessing post properties which have no proper API for them.It requires post provided explicitly and doesn't default to the current one, so in full for the current post it would be:
$slug = get_post_field( 'post_name', get_post() );
-
Vale lapena señalar que siestáen elbucle,puede usar `get_post_field` sin un segundo argumento ([docs] (https://developer.wordpress.org/reference/functions/get_post_field/))It is worth noting that if you are in the loop you can use `get_post_field` without second argument ([docs](https://developer.wordpress.org/reference/functions/get_post_field/))
- 13
- 2016-06-16
- jmarceli
-
- 2015-05-21
EDITAR 5 DE ABRIL DE 2016
Después debuscarmás confiabilidad,terminé haciendo esta respuesta a la siguientepublicación que conduce aestaedición : ( Asegúrese de comprobarlo )
Elmétodomás confiable hasta lafecha que seme ocurrióesel siguiente:
// Get the queried object and sanitize it $current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() ); // Get the page slug $slug = $current_page->post_name;
Deestamanera,está 99,9999% seguro de que obtiene los datos correctosen todomomento.
RESPUESTA ORIGINAL
Otra alternativamás segura aesteproblemaes usar
get_queried_object()
que contieneel objeto consultado actualpara obtenerel slug de lapágina que seencuentraen lapropiedadpost_name
. Esto sepuede utilizaren cualquier lugar de suplantilla.Sepuede usar
$post
,peropuede serpoco confiable ya que cualquier consultapersonalizada o códigopersonalizadopuede cambiarel valor de$post
,por lo que debeevitarsefuera deel lazo.Usar
get_queried_object()
para obtenerel objeto de lapágina actualesmuchomás confiable yesmenosprobable que semodifique,amenos queesté usandoelmalvadoquery_posts
que rompe la objeto de consulta,peroeso depende de usted.Puede utilizar lo anterior de la siguientemanera
if ( is_page() ) $slug = get_queried_object()->post_name;
EDIT 5 APRIL 2016
After digging for more reliability, I ended up doing this answer to the following post which leads to this edit: (Be sure to check it out)
The most reliable method till date I could come up with is the following:
// Get the queried object and sanitize it $current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() ); // Get the page slug $slug = $current_page->post_name;
This way, you are 99.9999% sure that you get the correct data every time.
ORIGINAL ANSWER
Another safer alternative to this problem is using
get_queried_object()
which holds the current queried object to get the page slug which is held by thepost_name
property. This can be used anywhere in your template.$post
can be used, but it can be unreliable as any custom query or custom code can change the value of$post
, so it should be avoided outside of the loop.Using
get_queried_object()
to get the current page object is much more reliable and is less likely to be modified, unless you are using the evilquery_posts
which breaks the main query object, but then that is all up to you.You can use the above as follow
if ( is_page() ) $slug = get_queried_object()->post_name;
-
Debo decir que `query_posts`noesmalo *** cuando quieres alterar la consultaprincipal ***,que sinembargonormalmenteno lo haces y amenudo se usamal :)I must say that `query_posts` is not evil ***when you want to alter the main query***, which however you usually don't and is often misused :)
- 0
- 2018-03-03
- jave.web
-
-
esto depende de la configuración delenlacepermanente.Si utiliza la configuración "simple",losenlaces se verán como `http://dominio/? P=123`,dejándolo con`? P=123`.this depends on the permalink settings. If you use the "simple" setting, links will look like `http://domain/?p=123`, leaving you with `?p=123`.
- 4
- 2016-10-14
- Mene
-
@Menees cierto,pero lapreguntaes cómo obtener unababosa,lo quegeneralmente significa que hay unaen la URL (GET arg `p`noes unababosa).@Mene true, but question is how to get slug which, usually, means there is one in the url (GET arg `p` is not a slug).
- 1
- 2020-02-17
- jave.web
-
Estees untrazador de líneastan ordenado: DThis is such a neat one liner :D
- 0
- 2020-03-13
- Sean Doherty
-
-
- 2012-02-13
Dadoelejemplo de código,parece que lo que realmentenecesitaes unenlace.Enese caso,puede usar get_permalink () ,quepuede usarsefuera del ciclo.Eso debería hacer lo quenecesita demaneramás confiable que usarelpost slug.
Given the code example, it looks like what you really need is a link. In that case, you can use get_permalink(), which can be used outside of the loop. That should do what you need more reliably than using the post slug.
-
Sinembargo,estaes la URL completa,no soloel slug.This is the full URL though, not just the slug.
- 4
- 2014-11-21
- Fred
-
- 2017-08-29
Puede que sea unapregunta antigua,pero creé lasfuncionesget_the_slug () ythe_slug ()basándomeen tus respuestas.
if ( !function_exists("get_the_slug") ) { /** * Returns the page or post slug. * * @param int|WP_Post|null $id (Optional) Post ID or post object. Defaults to global $post. * @return string */ function get_the_slug( $id = null ){ $post = get_post($id); if( !empty($post) ) return $post->post_name; return ''; // No global $post var or matching ID available. } /** * Display the page or post slug * * Uses get_the_slug() and applies 'the_slug' filter. * * @param int|WP_Post|null $id (Optional) Post ID or post object. Defaults to global $post. */ function the_slug( $id=null ){ echo apply_filters( 'the_slug', get_the_slug($id) ); } }
Might be an old question, but I created the functions get_the_slug() and the_slug() based on your answers.
if ( !function_exists("get_the_slug") ) { /** * Returns the page or post slug. * * @param int|WP_Post|null $id (Optional) Post ID or post object. Defaults to global $post. * @return string */ function get_the_slug( $id = null ){ $post = get_post($id); if( !empty($post) ) return $post->post_name; return ''; // No global $post var or matching ID available. } /** * Display the page or post slug * * Uses get_the_slug() and applies 'the_slug' filter. * * @param int|WP_Post|null $id (Optional) Post ID or post object. Defaults to global $post. */ function the_slug( $id=null ){ echo apply_filters( 'the_slug', get_the_slug($id) ); } }
-
- 2019-04-09
Sinceramente,noentiendopor quéninguna de las respuestas lo hace:
global $wp; $current_slug = $wp->request; // Given the URL of https://example.com/foo-bar if ($current_slug === 'foo-bar') { // the condition will match. }
Estofuncionaparatodas laspublicaciones,páginas y rutaspersonalizadas.
I honestly don't understand why none of the answers simply do:
global $wp; $current_slug = $wp->request; // Given the URL of https://example.com/foo-bar if ($current_slug === 'foo-bar') { // the condition will match. }
This works for all posts, pages, custom routes.
-
"Honestamente,noentiendopor quéninguna de las respuestas simplemente lo hace: ..." Probablementeporque `$ wp-> request`incluye laparte de la ruta * completa * de la URL,***incluidas las subcarpetas ***.Este código solofuncionaráen publicaciones/páginas queesténen elnivel raíz."I honestly don't understand why none of the answers simply do:..." Probably because `$wp->request` includes the *full* path part of the URL, ***including sub-folders***. This code will only work on posts/pages that are at root level.
- 1
- 2020-05-08
- FluffyKitten
-
Estaes lamejor respuesta aestapregunta:nadafuncionó hasta queprobéesto.This is the best answer to this question - nothing worked until I tried this.
- 0
- 2020-08-14
- Chris
-
- 2018-03-23
Si desea una respuestamás oculta,puede usar la siguiente consulta SQLparabuscartodas laspublicaciones que seanpublicaciones,páginas otaxonomíaspersonalizadasen cualquiermomento,incluso sino se ha activadoningúngancho como detodavía.
SQL sinformato:
SELECT `id`, `post_type` AS `type`, `post_author` AS `author`, `post_name` AS `slug`, `post_status` AS `status` FROM wp_posts WHERE `post_type` NOT IN ('attachment', 'nav_menu_item', 'revision') AND `post_status` NOT IN ('draft', 'trash') ORDER BY `id`;
Estofuncionainclusoen laprimera línea de su archivo defunciones,incluso antes de losganchos
mu_plugins_loaded
oinit
.<×@note×
Estoes asumiendo quetiene unprefijo debase de datosestándar
wp_posts
. Sinecesitateneren cuenta losprefijos de variables,puede obtener latabla depublicaciones correcta através de PHP conbastantefacilidad haciendo lo siguiente:<?php global $wpdb; $table = $wpdb->posts; $query = "SELECT `id`, `post_type` AS `type`, `post_author` AS `author`, `post_name` AS `slug`, `post_status` AS `status` FROM " . $table . " WHERE `post_type` NOT IN ('attachment', 'nav_menu_item', 'revision') AND `post_status` NOT IN ('draft', 'trash') ORDER BY `id`;"
Luego,ejecútelo con
$wpdb
,mysqli
o unainstancia dePDO
. Dado queno hayentrada de usuarioen esta consulta,es seguroejecutarla sin una declaraciónpreparada siempre quenoinyecteninguna variableen ella.Sugeriría almacenaresto como un valorestáticoprivado de una clase,para que sepueda acceder sintener que activar la consultanuevamentemás de una vezporpáginapara unmejor rendimiento,algo comoesto:
class Post_Cache { private static $post_cache; public function __construct() { //This way it skips the operation if it's already set. $this->initCache(); } public function get($id, $type = null) { if ( !(is_int( $id ) && array_key_exists( $id, self::$post_cache ) ) ) return false; } if ( !is_null( $type ) ) { //returns the specific column value for the id return self::$post_cache[$id][$type]; } //returns the whole row return self::$post_cache[$id]; } private function initCache() { if ( is_null(self::$post_cache) ) { $query = "..."; $result = some_query_method($query); //Do your query logic here. self::$post_cache = $result; { } }
<×Uso×
$cache = new \Post_Cache(); //Get the page slug $slug = $cache->get( get_the_ID(), 'slug'); if ($cache->get( get_the_ID() )) { //post exists } else { //nope, 404 'em } if ( $cache->get( get_the_ID(), 'status') === 'publish' ) { //it's public } else { //either check current_user_can('whatever_permission') or just 404 it, //depending whether you want it visible to the current user or not. } if ( $cache->get( get_the_ID(), 'type') === 'post' ) { //It's a post } if ( $cache->get( get_the_ID(), 'type') === 'page' ) { //It's a page }
Entiendes laesencia. Sinecesitamás detalles,puede obtenerlos como de costumbre con
new \WP_Post( get_the_ID() );
Esto lepermitirá verificar laspublicacionesen cualquiermomento,incluso siel ciclo de wordpressno ha llegado a unpuntoen el que su solicitud sea aceptable. Estaes una versión ligeramentemás optimizada de lamisma consultaejecutadaporelpropionúcleo de Wordpress. Estefiltratoda labasura queno desea que se devuelva y solo lebrinda una listabien organizada con laidentificación del autor relevante,eltipo depublicación,el slug y la visibilidad. Sinecesitamás detalles,puede obtenerlosnormalmente con
new \WP_Post($id);
,o usar cualquiera de las otrasfuncionesnativas de Wordpress con cualquiera de lasfilas de latabla relevantes,inclusofuera deelbucle.Utilizo una configuración similaren unpar demispropiostemas y complementospersonalizados,yfuncionabastantebien. Tambiénes seguro yno deja datosinternosflotandoen el ámbitoglobal donde sepuede anular como lamayoría de las cosasen Wordpress.
If you want a more under-the-hood answer, you can use the following SQL query to fetch all of the posts that are either posts, pages, or custom taxonomies at any time, even if no hooks have fired whatsoever as of yet.
Raw SQL:
SELECT `id`, `post_type` AS `type`, `post_author` AS `author`, `post_name` AS `slug`, `post_status` AS `status` FROM wp_posts WHERE `post_type` NOT IN ('attachment', 'nav_menu_item', 'revision') AND `post_status` NOT IN ('draft', 'trash') ORDER BY `id`;
This works even on the very first line of your functions file, even prior to the
mu_plugins_loaded
orinit
hooks.@note
This is assuming you have a standard database prefix
wp_posts
. If you need to account for variable prefixes, you can obtain the correct post table through PHP pretty easily by doing the following:<?php global $wpdb; $table = $wpdb->posts; $query = "SELECT `id`, `post_type` AS `type`, `post_author` AS `author`, `post_name` AS `slug`, `post_status` AS `status` FROM " . $table . " WHERE `post_type` NOT IN ('attachment', 'nav_menu_item', 'revision') AND `post_status` NOT IN ('draft', 'trash') ORDER BY `id`;"
Then run with either
$wpdb
,mysqli
, or aPDO
instance. Since there is no user input in this query, it is safe to run without a prepared statement as long as you do not inject any variables into it.I would suggest storing this as a private static value of a class, so it can be accessed without having to fire the query again more than once per page for best performance, something like this:
class Post_Cache { private static $post_cache; public function __construct() { //This way it skips the operation if it's already set. $this->initCache(); } public function get($id, $type = null) { if ( !(is_int( $id ) && array_key_exists( $id, self::$post_cache ) ) ) return false; } if ( !is_null( $type ) ) { //returns the specific column value for the id return self::$post_cache[$id][$type]; } //returns the whole row return self::$post_cache[$id]; } private function initCache() { if ( is_null(self::$post_cache) ) { $query = "..."; $result = some_query_method($query); //Do your query logic here. self::$post_cache = $result; { } }
Usage
$cache = new \Post_Cache(); //Get the page slug $slug = $cache->get( get_the_ID(), 'slug'); if ($cache->get( get_the_ID() )) { //post exists } else { //nope, 404 'em } if ( $cache->get( get_the_ID(), 'status') === 'publish' ) { //it's public } else { //either check current_user_can('whatever_permission') or just 404 it, //depending whether you want it visible to the current user or not. } if ( $cache->get( get_the_ID(), 'type') === 'post' ) { //It's a post } if ( $cache->get( get_the_ID(), 'type') === 'page' ) { //It's a page }
You get the gist. If you need further details, you can fetch them as per normal with
new \WP_Post( get_the_ID() );
This will let your check the posts at any time, even if the wordpress loop has not hit a point where it finds your request agreeable. This is a slightly more optimized version of the same query run by the Wordpress core itself. This one filters out all of the junk you would not want returned, and just gives you a nicely organized list with the relevant author id, post type, slug, and visibility. If you need further details, you can fetch them as per normal with
new \WP_Post($id);
, or use any of the other native Wordpress functions with any of the relevant table rows, even outside of the loop.I use a similar setup in a couple of my own custom themes and plugins, and it works pretty great. It's also secure and doesn't leave internal data floating around in the global scope where it can be overridden like most stuff in Wordpress does.
-
- 2018-11-24
Estaes lafunción que se debe usar cuando se desea recuperarel slugfuera delbucle.
get_post_field( 'post_name');
Aquí seencuentra la respuesta: Cómo recuperarel slug de lapágina actualen WordPress?
This is the function to use when wanting to retrieve the slug outside of the loop.
get_post_field( 'post_name');
Answer found here: How to Retrieve the Slug of Current Page in WordPress?
-
De hecho,pero debepasar $publicación o ID de lapublicación como segundo argumento.Indeed, but you need to pass $post or ID of the post as a second argument.
- 0
- 2019-10-17
- trainoasis
-
- 2015-02-12
Unpocomás adelanteen la respuesta de @Matthew Boynes,siestáinteresadoen obtenerel slugprincipal (si lo hubiera)también,estafunciónme resultó útil:
function mytheme_get_slugs() { if ( $link = get_permalink() ) { $link = str_replace( home_url( '/' ), '', $link ); if ( ( $len = strlen( $link ) ) > 0 && $link[$len - 1] == '/' ) { $link = substr( $link, 0, -1 ); } return explode( '/', $link ); } return false; }
Porejemplo,para agregar lasbabosas a la clase de cuerpo:
function mytheme_body_class( $classes ) { if ( $slugs = mytheme_get_slugs() ) { $classes = array_merge( $classes, $slugs ); } return $classes; } add_filter( 'body_class', 'mytheme_body_class' );
Just further on @Matthew Boynes answer, if you're interested in getting the parent slug (if any) also then I've found this function useful:
function mytheme_get_slugs() { if ( $link = get_permalink() ) { $link = str_replace( home_url( '/' ), '', $link ); if ( ( $len = strlen( $link ) ) > 0 && $link[$len - 1] == '/' ) { $link = substr( $link, 0, -1 ); } return explode( '/', $link ); } return false; }
Eg to add the slug(s) to the body class:
function mytheme_body_class( $classes ) { if ( $slugs = mytheme_get_slugs() ) { $classes = array_merge( $classes, $slugs ); } return $classes; } add_filter( 'body_class', 'mytheme_body_class' );
-
- 2017-02-14
Llamada depágina dinámicaen WordPress.
<?php get_template_part('foldername/'.basename(get_permalink()),'name'); ?>
Dynamic Page calling in WordPress.
<?php get_template_part('foldername/'.basename(get_permalink()),'name'); ?>
Estoyintentando recuperarel slug de lapágina actual de WordPressfuera delbucle.Eltítulo de lapágina vuelve con
wp_title ()
,pero ¿cómopuedo obtenerel slug?