GANESH JAGDHANE
¿Cómo puedo crear migas de pan? home->page->post
nombre cuando hacemos clic en el menú principal de cualquier página, abra la lista de publicaciones que crea la ruta de navegación home ->page
el nombre está bien, pero ahora, cuando hacemos clic en cualquier publicación, ese momento crea la ruta de navegación home->post
categoría name->post
El nombre es que cuando hacemos clic en el nombre de la categoría de publicación en el diseño de la ruta de navegación que se muestra diferente, queremos que vaya al enlace de la página, no al enlace de la categoría. así que necesitamos cuando abrimos cualquier publicación, necesitamos crear la ruta de navegación como esta home->page name->post
nombre, de modo que cuando hagamos clic en el nombre de la página, abra la página de lista de publicaciones, no la página de categoría.
nabeel khan
WordPress no proporciona la funcionalidad de migas de pan incorporadas. Por lo tanto, tendrá que usar un complemento o codificarlo usted mismo (o copiarlo de la referencia a continuación).
De hecho, el complemento o el código personalizado, si proporciona una funcionalidad similar, no hace mucha diferencia. Por lo tanto, use el que sea más conveniente para usted.
Si desea agregar un código personalizado, aquí hay algunos recursos que podría buscar en la búsqueda:
https://www.techpulsetoday.com/wordpress-breadcrumbs-sin-plugin/
https://www.thewebtaylor.com/articles/wordpress-creating-breadcrumbs-without-a-plugin
https://www.codexworld.com/wordpress-how-to-display-breadcrumb-sin-plugin/
https://gist.github.com/tinotriste/5387124
¡Puedes mirarlos y modificarlos como quieras!
¡Espero que ayude!
-
El primero funciona sin problemas. Bonificación: es agradable y compacto, no hace ese irritante código espaciado.
– Voros Imi
27 de junio de 2019 a las 14:46
-
Deben evitarse las respuestas de solo enlace.
– Ese chico brasileño
19 mayo 2020 a las 18:49
diarioamarino
No puedo entender cómo una respuesta con solo enlaces pegados puede llegar a tantos votos a favor. El enfoque regular de migas de pan de WordPress está dolorosamente desoptimizado, la mayoría de los que existen no se adaptan a los temas personalizados. Decidí crear una ruta de navegación basada en URL que, desde mi punto de vista, es mucho más eficiente y adaptable. Quería algo genérico, compatible con SEO, sin ningún estilo predeterminado. También necesitaba manejar adecuadamente las publicaciones y el título de las páginas.
Versión | |
---|---|
Requiere al menos WordPress: | 3.0.0 |
Requiere PHP: | 8.0 |
Probado hasta WordPress: | 6.0.1 |
La última versión está disponible en mi GitHub como un complemento no oficial de WordPress.
<?php
if ( ! function_exists( 'get_the_crumbs' ) ) {
/**
* Retrieve the crumbs.
*
* @since 1.0.0
*
* @return Array Crumbs array.
*/
function get_the_crumbs() {
/**
* $_SERVER["REQUEST_URI"] seems to be unreliable.
*
* Article "Is $_SERVER['REQUEST_SCHEME'] reliable?".
* @see https://stackoverflow.com/a/18008178/3645650
*
* $server_scheme is a native variable of Apache web server since its version 2.4.
* Naturally, if a variable is not set by the server, PHP will not include it in its global array $_SERVER.
*
* An alternative to $_SERVER['REQUEST_SCHEME'] is $_SERVER['HTTPS'] which set to a non-empty value if the script was queried through the HTTPS protocol.
*
* Article "How to find out if you're using HTTPS without $_SERVER['HTTPS']".
* @see https://stackoverflow.com/q/1175096/3645650
*/
if ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) {
$server_scheme="https";
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || ! empty( $_SERVER['HTTP_X_FORWARDED_SSL'] ) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ) {
$server_scheme="https";
} else {
$server_scheme="http";
};
/**
* $_SERVER["REQUEST_URI"] seems to be reliable.
* $_SERVER['REQUEST_URI'] will not be empty in WordPress, because it is filled in wp_fix_server_vars() (file wp-includes/load.php).
*
* Article "Is it safe to use $_SERVER['REQUEST_URI']?".
* @see https://wordpress.stackexchange.com/a/110541/190376
*/
$server_uri = $_SERVER['REQUEST_URI'];
/**
* $_SERVER["HTTP_HOST"] seems to be reliable.
*
* Article "How reliable is HTTP_HOST?".
* @see https://stackoverflow.com/a/4096246/3645650
*/
$server_host = $_SERVER["HTTP_HOST"];
if ( str_contains( $server_uri, '?' ) ) {
$server_uri = substr( $server_uri, 0, strpos( $server_uri, '?' ) );
};
if ( str_ends_with( $server_uri, "https://stackoverflow.com/" ) ) {
$server_uri = explode( "https://stackoverflow.com/", substr( $server_uri, 1, -1 ) );
} else {
$server_uri = explode( "https://stackoverflow.com/", substr( $server_uri, 1 ) );
};
$crumbs = array();
foreach ( $server_uri as $crumb ) {
$slug = esc_html( urldecode( $crumb ) );
$url = esc_url( $server_scheme . '://' . $server_host . "https://stackoverflow.com/" . substr( implode( "https://stackoverflow.com/", $server_uri ), 0, strpos( implode( "https://stackoverflow.com/", $server_uri ), $crumb ) ) . $crumb. "https://stackoverflow.com/" );
array_push( $crumbs,
array(
'slug' => $slug,
'url' => $url,
)
);
};
$banned_slugs = array();
$post_types = get_post_types(
array(
'public' => true,
),
'objects'
);
foreach ( $post_types as $post_type ) {
array_push( $banned_slugs, $post_type->name );
if ( isset( $post_type->rewrite['slug'] ) ) {
array_push( $banned_slugs, $post_type->rewrite['slug'] );
};
};
$taxonomies = get_taxonomies(
array(
'public' => true,
),
'objects'
);
foreach ( $taxonomies as $taxonomy ) {
array_push( $banned_slugs, $taxonomy->name );
if ( isset( $taxonomy->rewrite['slug'] ) ) {
array_push( $banned_slugs, $taxonomy->rewrite['slug'] );
};
};
$banned_crumbs = array();
foreach ( $banned_slugs as $banned_slug ) {
$slug = esc_html( $banned_slug );
$url = esc_url( $server_scheme . '://' . $server_host . "https://stackoverflow.com/" . substr( implode( "https://stackoverflow.com/", $server_uri ), 0, strpos( implode( "https://stackoverflow.com/", $server_uri ), $banned_slug ) ) . $banned_slug. "https://stackoverflow.com/" );
array_push( $banned_crumbs,
array(
'slug' => $slug,
'url' => $url,
)
);
};
$crumbs = array_filter( $crumbs, function( $crumb ) use ( $banned_slugs ) {
if ( ! in_array( $crumb['slug'], $banned_slugs ) && ! in_array( $crumb['url'], $banned_slugs ) ) {
return ! in_array( $crumb['slug'], $banned_slugs );
};
} );
return $crumbs;
};
};
if ( ! function_exists( 'the_bread' ) ) {
/**
* Display the bread, a formatted crumbs list.
*
* @since 1.0.0
*
* @param Array $ingredients The bread arguments.
* @param Array $ingredients['root'] Root crumb. Default to null.
* @param String $ingredients['root']['slug'] Root crumb slug.
* @param String $ingredients['root']['url'] Root crumb url.
* @param String $ingredients['separator'] The crumb's separator. The separator is not escaped.
* @param Integer $ingredients['offset'] Crumbs offset. Accept positive/negative Integer. Default to "0". Refer to array_slice, https://www.php.net/manual/en/function.array-slice.php.
* @param Integer $ingredients['length'] Crumbs length. Accept positive/negative Integer. Default to "null". Refer to array_slice, https://www.php.net/manual/en/function.array-slice.php.
*
* @return Array The formatted crumbs list.
*/
function the_bread( $ingredients = array() ) {
if ( empty( $ingredients['root'] ) ) {
$root = null;
} else {
$root = $ingredients['root'];
};
if ( empty( $ingredients['offset'] ) ) {
$offset = 0;
} else {
$offset = $ingredients['offset'];
};
if ( empty( $ingredients['length'] ) ) {
$length = null;
} else {
$length = $ingredients['length'];
};
$crumbs = get_the_crumbs();
if ( ! empty( $root ) ) {
array_unshift( $crumbs, $ingredients['root'] );
};
$crumbs = array_slice( $crumbs, $offset, $length );
if ( ! empty( $crumbs ) ) {
echo '<ol class="🍞 bread" itemscope itemtype="https://schema.org/BreadcrumbList">';
$i = 0;
foreach ( $crumbs as $crumb ) {
$i++;
if ( url_to_postid( $crumb['url'] ) ) {
$title = get_the_title( url_to_postid( $crumb['url'] ) );
} elseif ( get_page_by_path( $crumb['slug'] ) ) {
$title = get_the_title( get_page_by_path( $crumb['slug'] ) );
} else {
$title = ucfirst( str_replace( '-', ' ', $crumb['slug'] ) );
};
echo '<li class="crumb" itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
<a itemprop="item" href="' . $crumb['url'] . '">
<span itemprop="name">' . $title . '</span>
</a>
<meta itemprop="position" content="' . $i . '">
</li>';
if ( $i !== sizeof( $crumbs ) && ! empty( $ingredients['separator'] ) ) {
echo $ingredients['separator'];
};
};
echo '</ol>';
};
};
};
Mostrando el pan, una lista de migas formateada.
<?php
the_bread( $ingredients = array() );
Parámetros
Parámetro | Descripción |
---|---|
$ingredients |
(Opcional) Array de argumentos para exhibir el pan. |
$ingredients['root'] |
Array Miga de raíz. Predeterminado a null . |
$ingredients['root']['slug'] |
(Obligatorio si $ingredients['root'] ). Babosa de miga de raíz. |
$ingredients['root']['url'] |
(Obligatorio si $ingredients['root'] ). URL de migas de raíz. |
$ingredients['separator'] |
Separador de migas. El separador no se escapa. |
$ingredients['offset'] |
Compensación de migas. Aceptar positivo/negativo Integer . Predeterminado a 0 . Referirse a array_slice. |
$ingredients['length'] |
Longitud de las migas. Aceptar positivo/negativo Integer . Predeterminado a null . Referirse a array_slice. |
Ejemplo: El pan con un separador personalizado
<?php
$ingredients = array(
'separator' => '→',
);
the_bread( $ingredients );
Ejemplo: Visualización de las últimas 3 migas
<?php
$ingredients = array(
'offset' => -3,
'length' => 3,
);
the_bread( $ingredients );
Ejemplo: El pan con miga de raíz
<?php
$ingredients = array(
'root' => array(
'slug' => 'home',
'url' => get_home_url(),
),
);
the_bread( $ingredients );
Salida de estructura HTML5
<ol class="🍞 bread" itemscope="" itemtype="https://schema.org/BreadcrumbList">
<li class="crumb" itemprop="itemListElement" itemscope="" itemtype="https://schema.org/ListItem">
<a itemprop="item" href="http://example.com/where/">
<span itemprop="name">Where</span>
</a>
<meta itemprop="position" content="1">
</li>
>
<li class="crumb" itemprop="itemListElement" itemscope="" itemtype="https://schema.org/ListItem">
<a itemprop="item" href="http://example.com/where/is/">
<span itemprop="name">Is</span>
</a>
<meta itemprop="position" content="2">
</li>
>
<li class="crumb" itemprop="itemListElement" itemscope="" itemtype="https://schema.org/ListItem">
<a itemprop="item" href="http://example.com/where/is/my/">
<span itemprop="name">My</span>
</a>
<meta itemprop="position" content="3">
</li>
>
<li class="crumb" itemprop="itemListElement" itemscope="" itemtype="https://schema.org/ListItem">
<a itemprop="item" href="http://example.com/where/is/my/bread/">
<span itemprop="name">Bread</span>
</a>
<meta itemprop="position" content="4">
</li>
</ol>
Plantilla mínima de css (opcional)
.🍞,
.bread {
list-style-type: none;
margin:0;
padding:0;
}
.🍞 li,
.bread li {
display:inline-block;
}
.🍞 li.crumb:last-child a,
.bread li.crumb:last-child a {
text-decoration: none;
pointer-events: none;
color: inherit;
}
Recuperando las migas
Aunque le recomendamos que utilice the_bread()
función para mostrar y construir su propia ruta de navegación, puede usar get_the_crumbs()
para recuperar el objeto migas.
Ejemplo: Salida del objeto migas
<?php
var_dump( get_the_crumbs() );
-
Esto es realmente limpio y ligero. El único problema que he visto hasta ahora es que no hay ningún manejo de partes estáticas de enlaces permanentes, como
/category/
que no tiene ningún contenido, ni una ID de página. Sin embargo, probablemente podría personalizarlo para que no los imprima.– Inanis Atheos
12 de junio de 2021 a las 13:56
-
No noté el enlace de Github, ni que haya una versión posterior. Le echaré un vistazo. Y sí, podría crear esa página, supongo. Sin embargo, lo resolví con una serie de enlaces “prohibidos” para verificar antes de imprimir los resultados.
– Inanis Atheos
12/06/2021 a las 20:10
-
@Athoxx Versión
1.0.3
Filtra automáticamente los tipos de publicaciones y las migajas de raíz de taxonomías.– amarinediary
30/11/2021 a las 21:05
-
increíble, lo revisaré cuando regrese a un proyecto de WP 🙂
– Inanis Atheos
7 dic 2021 a las 22:27
¿Quiere decir solo mostrar una fila con migas de pan debajo del encabezado o simplemente tener una estructura de enlace para la URL?
– lisarko8077
17 de junio de 2018 a las 5:36