WordPress中如何在the_permalink()结果末尾添加锚点字符串?
解决WordPress子页面链接添加锚点(避免斜杠后出现锚点)
问题描述
我用wpse_list_child_pages_two函数生成网站子页面列表,希望给所有URL末尾添加#theheading锚点,点击后跳转到对应页面的theheading位置。但直接在HTML里给the_permalink()后加锚点时,锚点会出现在URL的斜杠之后(比如变成https://example.com/page/#theheading),想找个简单方法把锚点加在URL末尾斜杠的前面。目前试过直接在HTML里拼接的方式。
原函数代码:
/* List Child Pages version 2 */ <?php function wpse_list_child_pages_two( $cats = [] ) { global $post; $current_ID = $post->ID; if ( is_page() && $post->post_parent ) { $child_of = $post->post_parent; } else { $child_of = $current_ID; } // Get the category IDs for passed in category names for query. $cats = ( array ) $cats; $cats = array_map( 'get_cat_ID', $cats ); $args = [ 'post_type' => 'page', 'posts_per_page' => -1, 'post_parent' => $child_of, 'order' => 'ASC', 'orderby' => 'menu_order', 'category__not_in' => $cats, 'after' => 'top' ]; $parent = new WP_Query( $args ); if ( $parent->have_posts() ) : ?> <?php while ( $parent->have_posts() ) : $parent->the_post(); ?> <?php $current = function( $output ) use ( $current_ID ) { return get_the_ID() === $current_ID ? $output : ''; }; ?> <li class="nav-item nav-item<?php the_ID(); echo $current( ' active ' ); ?>"> <a href="<?php the_permalink(); ?>" <?php echo $current( 'aria-current="page"' ); ?>><?php the_title(); ?></a> </li> <?php endwhile; ?> <?php endif; wp_reset_postdata(); } ?>
之前尝试的代码(存在斜杠问题):
<a href="<?php the_permalink(); ?>#theheading" <?php echo $current( 'aria-current="page"' ); ?>><?php the_title(); ?></a>
解决方案
直接利用WordPress原生函数untrailingslashit()处理链接,移除URL末尾的斜杠后再拼接锚点,就能解决斜杠出现在锚点前的问题。
修改后的链接代码:
<a href="<?php echo untrailingslashit(get_the_permalink()) . '#theheading'; ?>" <?php echo $current( 'aria-current="page"' ); ?>><?php the_title(); ?></a>
原理说明
untrailingslashit()是WordPress内置函数,专门用于移除字符串末尾的斜杠,不管原URL是否有末尾斜杠,都能统一处理成无斜杠的格式。- 拼接
#theheading后,最终URL会变成https://example.com/page#theheading的形式,锚点位置符合需求。
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

