Как выделить текущую дочернюю страницу в пользовательском меню боковой панели? - PullRequest
0 голосов
/ 19 июня 2019

У меня есть боковое меню на сайте WordPress, которое просто выводит все дочерние страницы под этим родителем. Я пытаюсь выделить (или, надеюсь, добавить стрелку) текущую дочернюю страницу, которая выбрана. Я наткнулся на стену с моим ограниченным опытом PHP, чтобы понять, как это сделать.

Любая помощь будет принята с благодарностью. Соответствующий код ниже:

 <?php

                /* if the current pages has a parent, i.e. we are on a subpage */
                if($post->post_parent){
                    /* $children = wp_list_pages("title_li=&include=".$post->post_parent."&echo=0"); // list the parent page */
                    $children .= wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); // append the list of children pages to the same $children variable
                }

                /* else if the current page does not have a parent, i.e. this is a top level page */
                else {
                    //$children = wp_list_pages("title_li=&include=".$post->ID."&echo=0");    // include the parent page as well
                    $children .= wp_list_pages("title_li=&child_of=".$post->ID."&echo=0&");   // form a list of the children of the current page
                }

                /* if we ended up with any pages from the queries above */
                if ($children) { ?>
            <ul class="submenu">
                <?php echo $children; /*print list of pages*/ ?>
            </ul>
            <?php } ?>

Я предполагаю, что это будет в разделе вывода, но я просто не знаю, как настроить таргетинг на текущую просматриваемую дочернюю страницу и выделить ее соответствующим образом.

1 Ответ

0 голосов
/ 20 июня 2019

Мне было немного весело с этим. И мой результат может быть не совсем то, что вы искали, но я думаю, что это может быть лучше. Вкратце, приведенный ниже фрагмент позволяет легко определить иерархию страниц (родительский / дочерний) для текущей страницы. Таким образом, вы можете делать все виды чудесных вещей по желанию вашего сердца. Для вашего конкретного запроса я заставил пользовательскую функцию «custom_list_child_pages (...)» возвращать полный список ссылок из иерархии страниц, связанных с «текущей страницей».

Существует масса логики, связанной с ключевыми ситуациями, которые вы пытались решить. Вы должны быть в состоянии определить, когда вы находитесь на подстранице или родительской странице, вы должны иметь возможность вызывать эту маленькую функцию и изменять ее, чтобы она делала все, что вам нужно, со всеми соответствующими игроками (текущим, родительским) [или себя, если нет другого, дочерние страницы и т. д.).

Дайте мне знать, если это поможет вам, и если вы застряли с кодом или какими-либо другими аспектами, касающимися того, чего вы пытаетесь достичь, дайте мне знать, и я посмотрю, как я могу помочь вам в дальнейшем.

Код:

<?php

//die(var_dump($foo)); // Quickly check a variable value.

function custom_list_child_pages($the_current_page_id, $the_parent_page_id, $child_pages){
   $html_page_listing = '';

   // Get creative with the parent page.
   $the_parent_page = get_page( $the_parent_page_id );
   $html_page_listing .= "<h3>" . "<a href='$the_parent_page->guid'>$the_parent_page->post_title</a>" . "</h3>";

   // Get creative with the child pages.
   $html_page_listing .= "<h3>" . "Child pages:" . "</h3>";

   $html_page_listing .= "<ul>";

   // Iterate through child pages as desired.
   foreach ($child_pages as $key => $page) {
      $current_page = get_page_by_title( $page->post_title );
      $current_page_id = $page->ID;

      if ($current_page_id == $the_current_page_id) {
         // Do something great.
         $html_page_listing .= "<li> ->" . "<a href='$page->guid'>$page->post_title</a>" . "</li>";
      } else {
         $html_page_listing .= "<li>" . "<a href='$page->guid'>$page->post_title</a>" . "</li>";
      }
   }
   $html_page_listing .= "</ul>";
   return $html_page_listing;
}

global $post; // If outside the loop.

// Set up the objects needed.
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page', 'posts_per_page' => '-1'));

if ( is_page() && $post->post_parent ) {
   // This is a subpage.
   $the_current_page_id = $page_id;
   $the_parent_page_id = wp_get_post_parent_id( $post_ID );

   $the_child_pages = get_page_children( $the_parent_page_id, $all_wp_pages ); // Form a list of the children of the current page.
   $the_parent_page_id = wp_get_post_parent_id( $post_ID ); // Include the parent page as well.

   $menu = custom_list_child_pages($the_current_page_id, $the_parent_page_id, $the_child_pages); // ~append the list of children pages to the same $children variable
   echo $menu; // Print list of pages.

} else {
   // This is not a subpage.
   $the_current_page_id = $page_id;
   $the_parent_page_id = $page_id;

   $the_child_pages = get_page_children( $page_id, $all_wp_pages ); // Form a list of the children of the current page.
   $the_parent_page_id = $page_id; // Include the parent page as well.

   $menu = custom_list_child_pages($the_current_page_id, $the_parent_page_id, $the_child_pages);
   echo $menu; // Print list of pages.
}

?>

С уважением, Arty

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...