PHP短代码无法正确截断WordPress标题问题求助
问题解决:修复WordPress短代码中标题无法截断「-」后文本的问题
问题分析
你的代码处理标题截断时,使用了长破折号'–'进行分割,但实际文章标题里的是短减号'-'——两者是不同字符,导致分割匹配失败,无法去除「-」之后的文本。另外,substr($title, 3)属于固定长度截取,若标题开头数字位数变化(比如1位或3位数字),就会出现处理错误。
修复方案
- 替换分割字符为短减号
'-',同时兼容可能存在的长破折号,自动处理符号前后的空格; - 用正则表达式替代固定长度的
substr,更稳定地移除标题开头的数字部分。
修改后的关键代码片段
while ( $the_query->have_posts() ) { $the_query->the_post(); $title = get_the_title(); // 移除标题开头的任意位数数字及后续空格 $title = preg_replace('/^\d+\s/', '', $title); // 按短减号/长破折号分割标题,取分割后的第一部分,自动忽略符号前后空格 $title = preg_split('/\s*[-–]\s*/', $title)[0]; $output .= '<li class="sidebar-small-txt"><a href="' . get_permalink() . '">' . $title . '</a></li>'; }
完整修改后的短代码
function show_cat_posts_func( $atts ) { global $post; $url_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $url_segments = explode('/', trim($url_path, '/')); $category_from_url = isset($url_segments[0]) ? $url_segments[0] : ''; $a = shortcode_atts( array( 'category' => $category_from_url, ), $atts ); $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'category_name' => $a['category'], 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC', 'post__not_in' => isset($post) ? array($post->ID) : array(), ); $the_query = new WP_Query( $args ); $output = ''; if ( $the_query->have_posts() ) { $output .= '<p class="sidebar-heading-txt">' . $a['category'] . '</p>'; $output .= '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); $title = get_the_title(); // 移除标题开头的数字及后续空格 $title = preg_replace('/^\d+\s/', '', $title); // 按短减号/长破折号分割标题,取前半部分 $title = preg_split('/\s*[-–]\s*/', $title)[0]; $output .= '<li class="sidebar-small-txt"><a href="' . get_permalink() . '">' . $title . '</a></li>'; } $output .= '</ul>'; } else { $output .= '<p>Keine Beiträge in dieser Kategorie gefunden.</p>'; } wp_reset_postdata(); return $output; } add_shortcode( 'show_cat_posts', 'show_cat_posts_func' );
内容的提问来源于stack exchange,提问作者moinmobility
相关产品推荐
相关产品推荐

