如何在WordPress中替换the_title中的文本?

3

我希望能够替换wp标题中的文本,实际上有一个受欢迎文章的小部件。
我想要替换此小部件输出中的文本,所以我搜索了小部件功能并找到了以下代码:

foreach($popular as $post) :
        setup_postdata($post);
        ?>
    <li>
        <a href="<?php the_permalink(); ?>">
            <?php if ( $show_thumb3 == 1 ) : ?>
                <?php the_post_thumbnail('widgetthumb',array('title' => '')); ?>
            <?php endif; ?>
            <?php the_title(); ?>   
        </a>
blah blah blah...

我尝试将这一行 <?php the_title(); ?> 改为:

<?php
    $wptitle = the_title();
    $wptitle = str_replace('textbefore', 'textafter', $wptitle);
    echo $wptitle;
?>

但是在实际网站中没有任何作用,也没有任何影响!
我如何替换小部件输出标题中的文本?
如果有两个字符串需要替换,我该怎么办?
我应该使用类似这样的东西吗?:

    <?php
    $wptitle = the_title();
    $wptitle = str_replace('textbefore', 'textafter', $wptitle) && str_replace('text2before', 'text2after', $wptitle);
    echo $wptitle;
?>

the_title() 函数用于显示文章标题,而流行的文章插件也会从文章部分显示热门文章,因此如果您想更改某些内容或添加内容,可以将其附加到 the_title() 或需要替换文章标题。 - Manthan Dave
2个回答

3
<?php
$wptitle = the_title();
$wptitle = str_replace('textbefore', 'textafter', $wptitle);
echo $wptitle;
?>

替换为

<?php
$wptitle = get_the_title($post->id);
$wptitle = str_replace('textbefore', 'textafter', $wptitle);
echo $wptitle;
?>

1
完美运作!如果有两个我想替换的字符串,怎么办?我用了&&但它只返回1,什么都没有。 - M. Safari
不好意思,我没听懂你的意思,请再解释一下。 - Deepti chipdey
谢谢,这很有帮助。如果能够提供更多关于这两种方法(get_the_title() vs the_title())之间的区别的信息就更好了。我查阅了WordPress Codex,它们似乎都返回标题。为什么在这种情况下它起作用呢?谢谢。 - FNunez

2

试试这个

$wptitle = get_the_title( get_the_ID() );
$wptitle = str_replace('textbefore', 'textafter', $wptitle);
echo $wptitle;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接