WordPress 内容在使用 if 语句或开关/大小写时消失


wordpress content disappears when using if statement or switch/case

当我创建一个函数(在child-theme/functions.php中)来修改the_content()中的文本时,以下函数运行良好。

function my_text_changes ( $text ) {
    $text = str_replace( 'My Site Name', '<em>My Site Name</em>', $text );
    return $text;
}
add_filter( 'the_content','my_text_changes' );

此函数仅修改文本的一部分(多次)。当我更改函数以便我可以修改文本的更多部分时,我采用了相同的变量并str_replace并将其放入开关/case 中(也尝试了 if 语句),所有内容都消失了。

function my_text_changes ( $text ) {
switch( $text ) { 
case "My Site Name":
    $text = str_replace( 'My Site Name', '<em>My Site Name</em>', $text );
    return $text;
break;
}
}
add_filter( 'the_content','my_text_changes' );

我想构建多个案例,但无法让第一个案例正常工作。如果我将开关/大小写更改为 if 语句,情况也是如此。我尝试将$text =return $text更改为$newtext =return $newtext无济于事。有什么想法吗?

您传递到那里的$text参数包含全部内容。您switch分配永远不会是真的(除非整个内容由"我的网站名称"组成),并且您的文本不会被替换。

所有内容消失的原因是您必须在 switch 语句(或您的 if/else s)之外return $text 变量,否则它将不显示任何内容(基本上您正在用任何内容替换整个内容)。

事实上,如果我正确理解您的问题,您在没有任何if/elseswitch的情况下运行您的str_replace就足够了。

编辑:

虽然原始答案有效,但有更好的方法。您在评论中争辩说,第二个$text将覆盖第一个赋值,这是真的,但不是问题,因为前一个已经是正确替换字符串的文本。试一试,自己看看吧。

无论如何,我检查了文档的str_replace,它确实接受array s作为参数,因此您的问题可能会像这样解决:

function my_text_changes ( $text ) {
    $searches = array( 'My Site Name', 'a second string' );
    $replaces = array( '<em>My Site Name</em>', 'a <strong>second</strong> string' );
    $new_text = str_replace( $searches, $replaces, $text );
    /* ... */
    return $new_text;
}

原答案

只需做:

function my_text_changes ( $text ) {
    $text = str_replace( 'My Site Name', '<em>My Site Name</em>', $text );
    $text = str_replace( 'second_string', 'replacement', $text);
    /* ... */
    return $text;
}

不应该在休息前使用 return 语句。

但这个问题似乎与引用的代码不同。您可以检查主机上的 php 错误日志并共享吗?