Как мне настроить вывод wp_list_pages (), чтобы я мог обернуть ссылку в свой собственный HTML? - PullRequest
0 голосов
/ 11 апреля 2019

Я новичок в WordPress и хочу создать меню. С помощью wp_list_pages() я могу создать список ссылок, обернутых в теги <li>.

Это нормально, но я хочу добавить к ним свои собственные классы (а также, возможно, изменить элементы, обертывающие их).

Я просмотрел https://developer.wordpress.org/reference/functions/wp_list_pages/ и несколько сообщений на форуме, но не смог найти ничего, что указывает мне правильное направление.

Как мне настроить вывод wp_list_pages?

Ответы [ 2 ]

0 голосов
/ 11 апреля 2019

Я нашел два пути,

Использование фильтров и регулярных выражений

Добавить следующее к вашей теме functions.php file.

function clean_wp_list_pages($menu) {
    // Remove redundant title attributes
    $menu = remove_title_attributes($menu);
    // Remove protocol and domain name from href values
    $menu = make_href_root_relative($menu);
    // Give the list items containing the current item or one of its ancestors a class name
    $menu = preg_replace('/class="(.*?)current_page(.*?)"/','class="sel"',$menu);
    // Remove all other class names
    $menu = preg_replace('/ class=(["\'])(?!sel).*?\1/','',$menu);
    // Give the current link and the links to its ancestors a class name and wrap their content in a strong element
    $menu = preg_replace('/class="sel"><a(.*?)>(.*?)<\/a>/','class="sel"><a$1 class="sel"><strong>$2</strong></a>',$menu);
    return $menu;
}
add_filter( 'wp_list_pages', 'clean_wp_list_pages' );

Использование пользовательской функции ходунка

Это то же самое, что и выше. Добавьте это в ваш файл functions.php:

class Clean_Walker extends Walker_Page {
    function start_lvl(&$output, $depth) {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<ul>\n";
    }

    function start_el(&$output, $page, $depth, $args, $current_page) {
        if ( $depth )
            $indent = str_repeat("\t", $depth);
        else
            $indent = '';
        extract($args, EXTR_SKIP);
        $class_attr = '';
        if ( !empty($current_page) ) {
            $_current_page = get_page( $current_page );
            if ( (isset($_current_page->ancestors) && in_array($page->ID, (array) $_current_page->ancestors)) || ( $page->ID == $current_page ) || ( $_current_page && $page->ID == $_current_page->post_parent ) ) {
                $class_attr = 'sel';
            }
        } elseif ( (is_single() || is_archive()) && ($page->ID == get_option('page_for_posts')) ) {
            $class_attr = 'sel';
        }
        if ( $class_attr != '' ) {
            $class_attr = ' class="' . $class_attr . '"';
            $link_before .= '<strong>';
            $link_after = '</strong>' . $link_after;
        }
        $output .= $indent . '<li' . $class_attr . '><a href="' . make_href_root_relative(get_page_link($page->ID)) . '"' . $class_attr . '>' . $link_before . apply_filters( 'the_title', $page->post_title, $page->ID ) . $link_after . '</a>';

        if ( !empty($show_date) ) {
            if ( 'modified' == $show_date )
                $time = $page->post_modified;
            else
                $time = $page->post_date;
            $output .= " " . mysql2date($date_format, $time);
        }
    }
}

Чтобы использовать это, вам нужно вызвать wp_list_pages с параметром walker.

<?php
$walker = new Clean_Walker();
wp_list_pages( array(
    'title_li' => '',
    'walker' => $walker,
    ) );
?>

Источник: здесь

0 голосов
/ 11 апреля 2019

Этого можно достичь, переопределив класс .page-item. Проверьте здесь для более подробной информации https://developer.wordpress.org/reference/functions/wp_list_pages/#more-information

Если вам нужно добавить пользовательские классы или изменить способ отображения списка, вы можете прикрепить функцию Walker https://developer.wordpress.org/reference/classes/walker/

Пример можно найти по адресу https://developer.wordpress.org/reference/classes/walker_nav_menu/

class Custom_Walker_Page extends Walker_page {

function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 )
{
   //You can make your change here
}

}
$args = array(
.....
.....
'walker' => new Custom_Walker_page()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...