Mostrar páginas padre e hijas en las migas de pan

7 mar 2012, 16:12:38
Vistas: 18K
Votos: 3

Estamos intentando crear una función para las migas de pan que muestre no solo la ruta a la página actual, sino también a otras páginas con la misma página padre.

Por ejemplo, en ejemplo.com/padre1/hijo3, las migas de pan mostrarían Inicio > Padre1 > Hijo1 > Hijo2 > Hijo3 > Hijo4 en lugar de simplemente Inicio > Padre1 > Hijo3.

Estamos usando una versión modificada del script de migas de pan de http://dimox.net/wordpress-breadcrumbs-without-a-plugin/:

function dimox_breadcrumbs( $args = array() ) {
$defaults = array(
    'delimiter'         => '»',
    'home'              => 'Inicio',
    'before'            => '<span class="current">',
    'after'             => '</span>',
    'before_wrapper'    => '<div id="crumbs">',
    'after_wrapper'     => '</div>',
    'before_link'       => '<li>',
    'after_link'        => '</li>'
);

$opts = wp_parse_args( $args, $defaults );

$delimiter = $opts['delimiter'];
$home = $opts['home']; // texto para el enlace 'Inicio'
$showCurrent = 0; // 1 - mostrar título actual en migas de pan, 0 - no mostrar
$before = $opts['before']; // etiqueta antes del elemento actual
$after = $opts['after']; // etiqueta después del elemento actual
$b_link = $opts['before_link'];
$a_link = $opts['after_link'];
$title = '';
$sub_title = '';

if ( 1 || (!is_home() && !is_front_page()) || is_paged() ) {

    echo $opts['before_wrapper'];

    $out = '<ul>';

    global $post;
    $homeLink = get_bloginfo('url');
    $out .= $b_link . '<a href="' . $homeLink . '">' . $home . '</a>' . $a_link . $delimiter;

    if ( is_category() ) {
        global $wp_query;
        $cat_obj = $wp_query->get_queried_object();
        $thisCat = $cat_obj->term_id;
        $thisCat = get_category($thisCat);
        $parentCat = get_category($thisCat->parent);
        if ($thisCat->parent != 0) {
            $out .= $b_link . (get_category_parents($parentCat, TRUE, $delimiter)) . $a_link;        
        }

        $title = __( 'Archivo de la categoría "%"', LANGUAGE_ZONE );
        $sub_title = single_cat_title('', false);
        $title = str_replace( '%', $sub_title, $title );

    }elseif ( is_day() ) {
        $out .= $b_link . '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a>' . $a_link . $delimiter;
        $out .= $b_link . '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a>' . $a_link . $delimiter;
        $title = $sub_title = get_the_time('d');

    }elseif ( is_month() ) {
        $out .= $b_link . '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a>' . $a_link . $delimiter;
        $title = $sub_title = get_the_time('F');

    }elseif ( is_year() ) {
        $title = $sub_title = get_the_time('Y');

    }elseif ( is_search() ) {
        $title = __( 'Resultados de búsqueda para "%"', LANGUAGE_ZONE );
        $sub_title = get_search_query();
        $title = str_replace( '%', $sub_title, $title );

    }elseif ( is_single() && !is_attachment() ) {
        if ( get_post_type() != 'post' ) {
            $post_type = get_post_type_object(get_post_type());
            $slug = $post_type->rewrite;
//     echo $b_link . $post_type->labels->singular_name . $a_link . $delimiter;
//     echo $b_link . '<a href="' . $homeLink . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a>' . $a_link . $delimiter;
            $title = $sub_title = get_the_title();
        }else {
// blog y otros contenidos
            $menu_data = dt_current_menu_item();

//                $cat = get_the_category(); $cat = $cat[0];
//                echo $b_link . get_category_parents($cat, TRUE, ' ' . $delimiter . ' ') . $a_link;
            $out .= $b_link . '<a href=' . esc_url($menu_data['link']) . '>' . $menu_data['title'] . '</a>' . $a_link;
            $title = get_the_title();
            $sub_title = $menu_data['title'];
        }

    }elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) {
        $post_type = get_post_type_object(get_post_type());
        $title = $sub_title = $post_type->labels->singular_name;

    }elseif ( is_attachment() ) {
        $parent = get_post($post->post_parent);
//            $cat = get_the_category($parent->ID); $cat = $cat[0];
//            $out .= get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
        $out .= $b_link . '<a href="' . get_permalink($parent) . '">' . $parent->post_title . '</a>'  . $a_link . $delimiter;
        $title = $sub_title = get_the_title();

    }elseif ( is_page() && !$post->post_parent ) {
        $title = $sub_title = get_the_title();

    }elseif ( is_page() && $post->post_parent ) {
        $parent_id  = $post->post_parent;
        $breadcrumbs = array();
        while ($parent_id) {
            $page = get_page($parent_id);
            $breadcrumbs[] = $b_link . '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>' . $a_link;
            $parent_id  = $page->post_parent;
        }
        $breadcrumbs = array_reverse($breadcrumbs);
        foreach ($breadcrumbs as $crumb) $out .= $crumb . $delimiter;
        $title = $sub_title = get_the_title();

    }elseif ( is_tag() ) {
        $title = __( 'Publicaciones etiquetadas "%"', LANGUAGE_ZONE );
        $sub_title = single_tag_title('', false);
        $title = str_replace( '%', $sub_title, $title );

    }elseif ( is_author() ) {
        global $author;
        $userdata = get_userdata($author);
        $title = __( 'Artículos publicados por %', LANGUAGE_ZONE );
        $sub_title = $userdata->display_name;
        $title = str_replace( '%', $sub_title, $title );

    }elseif ( is_404() ) {
        $title = $sub_title = __( 'Error 404', LANGUAGE_ZONE );

    }elseif( is_home() ) {
        $title = $sub_title = __( 'Blog', LANGUAGE_ZONE );

    }

    if( strlen($title) > 50 ) {
        $title = substr( $title, 0, 50 );
        $title .= '...';
    }

    $out .= $before . $title . $after;

    if ( get_query_var('paged') ) {
        if( is_category() ||
            is_day() ||
            is_month() ||
            is_year() ||
            is_search() ||
            is_tag() ||
            is_author() )
        {
            $out .= ' (';
        }

        $out .= '&nbsp;' . __('Página', LANGUAGE_ZONE) . ' ' . get_query_var('paged');

        if( is_category() ||
            is_day() ||
            is_month() ||
            is_year() ||
            is_search() ||
            is_tag() ||
            is_author() )
        {
            $out .= ')';
        }
    }

    $out .= '</ul>';

    if( $opts['show_trail'] ) {
        echo $out;
    }

    echo '<h1>' . dt_first_letter_filter( $sub_title ) . '</h1>';

    echo $opts['after_wrapper'];

}
} // fin dimox_breadcrumbs

¿Alguna idea? Lo agradeceríamos mucho.

3
Comentarios

cuando coloco esto en mi tema (después de comentar la función dt_first_letter_function() que no tengo)... obtengo padre > hijo > nieto > estás aquí. ¿Cuál es exactamente el problema?

helgatheviking helgatheviking
7 mar 2012 16:48:00

Me gustaría que mostrara otras páginas del mismo nivel. En lugar de solo mostrar la ruta/dónde has estado, mostraría otras páginas hijas con el mismo padre. Si Parent1 tiene 4 páginas hijas, mostraría las 4 páginas hijas con estilo CSS para resaltar la página actual (hija). En otras palabras, mostraría Inicio > Parent1 > Child1 > Child2 > Child3 (Página Actual) > Child4. Un ejemplo de esto usando categorías se puede encontrar aquí: enlace. ¿Crees que hay alguna manera de hacer esto sin tener que crear un menú personalizado en cada página?

Nick Nick
7 mar 2012 17:13:37

nick, disculpa, no entendí lo que querías ya que asumí que child1 e child implicaban una jerarquía de padre > hijo > nieto en lugar de una relación de hermanos. He publicado una solución que debería darte las páginas hermanas para cualquier página en particular

helgatheviking helgatheviking
7 mar 2012 17:45:54
Todas las respuestas a la pregunta 1
5

No sé cómo integrarlo en tus migas de pan... que por naturaleza creo que son jerárquicas.

Pero esto debería darte una lista de las páginas que tienen el mismo padre que la página en la que estás (también conocidas como sus hermanas), aunque de una forma totalmente sin estilo.

global $post;

$args = array('child_of' => $post->post_parent, 'exclude'=> $post->ID);
if ($post->post_parent) $pages = get_pages($args);

if ($pages) foreach ($pages as $page): 
    echo $page->post_title .'<br/>';
endforeach;

Si listas tu página actual y luego enumeras sus hermanas, entonces puedes recrear programáticamente lo que estás buscando, creo.

edición 1: configura postdata para que podamos usar get_permalink(), get_the_title() dentro de un "bucle" etc. en lugar de métodos de objeto. get_permalink() obtiene la URL del elemento actual en el bucle

global $post;

$args = array('child_of' => $post->post_parent, 'exclude'=> $post->ID);
if ($post->post_parent) $pages = get_pages($args);

if ($pages) :

//almacena la variable $temp
$temp = $post;

$siblings = '<ul>';

foreach ($pages as $post): setup_postdata($post); 

    $siblings .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endforeach;

//restaura la variable $post
$post = $temp;

$siblings .= '</ul>';

echo $siblings;

endif;

Los argumentos son diferentes, pero http://codex.wordpress.org/Function_Reference/get_posts#Reset_after_Postlists_with_offset es el bucle foreach con el que suelo trabajar. También es para get_posts, pero get_pages funciona igual excepto que solo devuelve páginas.

7 mar 2012 17:44:28
Comentarios

¡Muchas gracias, Helga! Eso funcionó perfectamente para que aparecieran las otras páginas... ¿cómo haría para que tengan enlaces? Lo siento, soy nuevo en PHP. ¡Realmente aprecio tu ayuda!

Nick Nick
7 mar 2012 18:25:22

¡¡¡GRACIAS!!! Ha movido las páginas hermanas a la misma línea, pero por alguna razón todavía no enlazan a sus respectivas páginas...

Nick Nick
8 mar 2012 02:06:31

"¿páginas hermanas en la misma línea?" Las puse en una lista desordenada para que puedas darles el estilo que quieras. Los enlaces funcionan bien para mí. Acabo de probar de nuevo. ¿Has cambiado algo? Esto no está pensado para pegarlo en la función de breadcrumbs, así que probablemente podría... simplemente no lo probé de esa manera.

helgatheviking helgatheviking
8 mar 2012 02:48:07

Sí, lo siento. Necesitaba ajustar algo en CSS. Ahora funciona perfectamente. ¡Gracias por toda tu ayuda! ¡Realmente lo aprecio!

Nick Nick
8 mar 2012 13:01:02

de nada. si mi respuesta resolvió tu pregunta ¿podrías marcarla como la respuesta? (la marca de verificación verde)

helgatheviking helgatheviking
8 mar 2012 16:21:12