【问题标题】:WordPress wp_list_pages - Change children of parent from URLS into #anchor linksWordPress wp_list_pages - 将父级的子级从 URLS 更改为 #anchor 链接
【发布时间】:2019-10-09 20:51:54
【问题描述】:

我正在使用 wp_list_pages 设置侧导航菜单,我想将子链接从 URL 转换为锚链接,即 #link 而不是由 wp_list_pages 生成的当前 https://example.com/link

我尝试使用以下代码:

<?php
    $my_pages = wp_list_pages('echo=0&title_li=&child_of=5&depth=1');

    $pieces = explode('"', $my_pages);
    $i = 5;

    $j = 3;
    $limit = count($pieces);

    for (;$i<$limit;) {
        $tmp1 = '#'.$pieces[$j];

        $pieces[$i] = $tmp1;
        $i = $i+6;

        $j = $j+6;
    }
    $tmp2 = implode('"',$pieces);

    echo $tmp2;
?>

但它似乎已经很老了,我不知道如何将它正确地实施到我当前的结构中。也许这段代码对我正在尝试做的事情没有用,但我找不到任何可行的方法。

这是我目前拥有的:

<div class="hero-container">

          <?php
          global $children;
          global $post;
          if ( $post->post_parent ) {
            $children = wp_list_pages( array(
              'title_li' => '',
              'child_of' => $post->post_parent,
              'echo'     => 0
            ) );
             } else {
            $children = wp_list_pages( array(
              'title_li' => '',
              'child_of' => $post->ID,
              'echo'     => 0
              ) );
            }
            if ( $children ) : ?>

          <?php echo '<div class="hero-side-menu">', '<h1>', get_the_title(), '</h1>', '<ul>', $children, '</ul>', '</div>' ?>

         <?php endif; ?>
  </div>

任何建议都将不胜感激,因为我已经尝试解决了几天但一无所获......也希望得到解释,因为我正在努力了解我哪里出错了!

我需要将父页面的子页面修改为具有#anchor 链接而不是 URL,因为我已将页面压缩为它们的父页面,但仍希望将它们作为侧面菜单中的选项。

澄清:我有一个页面,其中包含我称为父母的子页面,但它们确实是孩子。我想保留子页面的 URL,然后制作子页面的子页面 #links。

【问题讨论】:

  • 什么是全局$children; ?
  • 用于将变量的作用域改为全局。

标签: php html wordpress


【解决方案1】:

这在一定程度上取决于您希望锚文本是什么。无论是 ID 还是标题等。但您可以根据需要进行修改。

您可能想改用 get_pages(),这样您就可以更好地控制输出。类似于以下内容:

<div class="hero-container">

  <?php        
  global $post;

  $current_page_title = $post->post_title; // current page title

  $child_pages = 
      get_pages(
        array(
         'child_of' => $post->ID       
        ),
      );

  if ($child_pages) : ?>

    <div class="hero-side-menu">
      <h1><?php echo $current_page_title; ?></h1>

      <ul>

       <?php foreach ($child_pages as $page) : ?>

          <li><a href="<?php echo '#' . $page->post_title; ?>"><?php echo $page->post_title; ?></a></li>

       <?php endforeach; ?>

      </ul>

    </div>

  <?php endif; ?>

</div>

【讨论】:

  • 非常感谢您的回复。虽然这确实让我在某些方面更接近我的目标,但它并没有完全解决。也许我应该澄清说我希望孩子的链接是 URLS 和孩子的孩子(孙子?)是 IDs 。不过,我也许可以将其转化为解决方案,因此非常感谢!干净的代码!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
相关资源
最近更新 更多