WordPress短代码优化:保留URL连字符,移除输出文本连字符
解决WordPress短代码中Topic显示格式问题
你需要在短代码里新增一个变量,把带连字符的topic转换成空格分隔的格式用于文本显示,URL部分保留原带连字符的参数即可。具体修改如下:
修改后的完整代码
function moretopics($atts){ $default = array( 'year' => 'year-8', 'topic' => 'algebra', 'yearnohyphen' => 'Year 8', ); $attributes = shortcode_atts($default, $atts); // 新增变量:将topic中的连字符替换为空格,用于文本显示 $display_topic = str_replace('-', ' ', $attributes['topic']); $s2writing = "<h4 align='center'>For more " . $display_topic . " worksheets see <a href='http://websitename.com/" . $attributes['year'] . "-maths-worksheets/" . $attributes['year'] . "-" . $attributes['topic'] . "-worksheets' style='text-decoration:underline'>" . $attributes['yearnohyphen'] . " " . $display_topic . " Worksheets</a></h4><hr/>"; return $s2writing; } add_shortcode('moretopics', 'moretopics');
修改说明
- 新增
$display_topic变量:用str_replace('-', ' ', $attributes['topic'])把参数里的连字符替换成空格,得到适合显示的格式(比如把Mental-Arithmetic转换成Mental Arithmetic)。 - 替换文本显示部分:把原代码中所有用于显示topic名称的
$attributes['topic']换成$display_topic,URL拼接部分依然保留原$attributes['topic'],确保链接地址正确。
调用原短代码[moretopics year="Year-8" topic="Mental-Arithmetic" yearnohyphen="Year 8"]时,输出就会变成你期望的格式:
For more Mental Arithmetic worksheets see Year 8 Mental Arithmetic worksheets
内容的提问来源于stack exchange,提问作者Garden Darts
相关产品推荐
相关产品推荐

