WordPress / PHP / Shortcode:从输出中删除连字符
问题在于当话题名称中有空格时,我需要在对应链接中加上连字符以指向该话题——如何在输出文本中移除连字符但在URL中保留?
我试过str_replace(" ", "-"), 但我不确定。下面是短码
function moretopics($atts){
$default = array(
'year' => 'year-8',
'topic' => 'algebra',
'yearnohyphen' => 'Year 8',
);
$attributes = shortcode_atts($default, $atts);
$s2writing = "<h4 align='center'>For more " . $attributes['topic'] . " worksheets see <a href='http://websitename.com/" . $attributes['year'] . "-maths-worksheets/" . $attributes['year'] . "-" . $attributes['topic'] . "-worksheets' style='text-decoration:underline'>" . $attributes['yearnohyphen'] . " " . $attributes['topic'] . " Worksheets</a></h4><hr/>";
return "" . $s2writing . "";
}
add_shortcode('moretopics', 'moretopics');
例如,短码是:
[moretopics year="Year-8" topic="Mental-Arithmetic" yearnohyphen="Year 8"]
显示为:
For more Mental-Arithmetic worksheets see Year 8 Mental-Arithmetic worksheets
但我希望显示得更自然一些,如:
For more Mental Arithmetic worksheets see Year 8 Mental Arithmetic worksheets
解决方案
我已经尝试了str_replace(" ", "-"), 但我不确定。以下是短码
非常接近,但应该用另一种方法——在属性中自然地以带空格的形式写成 topic="Mental Arithmetic",然后使用 str_replace() 动态创建一个仅用于URL的带连字符版本,同时保留原本带空格的版本用于显示文本。
下面是如何更新你的函数($s2writing已更改,请按需要更新):
function moretopics($atts) {
$default = [
'year' => 'year-8',
'topic' => 'algebra',
'yearnohyphen' => 'Year 8',
];
$attributes = shortcode_atts($default, $atts);
// URL-friendly version by replacing spaces with hyphens
$topic_url = str_replace(" ", "-", $attributes['topic']);
// Using $attributes['topic'] for the text, and $topic_url for the href link
$s2writing = "<h4 align='center'>For more "
. $attributes['topic']
. " worksheets see <a href='http://websitename.com/"
. $attributes['year']
. "-maths-worksheets/"
. $attributes['year']
. "-" . $topic_url
. "-worksheets' style='text-decoration:underline'>"
. $attributes['yearnohyphen']
. " " . $attributes['topic']
. " Worksheets</a></h4><hr/>";
return $s2writing;
}
add_shortcode('moretopics', 'moretopics');
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。