繁体   English   中英

使用str_replace更改PHP模板中的文本

[英]Using str_replace to change text within PHP template

我试图在基于WooCommerce的WP网站上更改一些文本。

本质上,通过使用str_replace的过滤器,我试图将文本“%s对%s的评论”更改为其他内容。

该文本包含在single-product-reviews.php文件中。

见下文:

<h2><?php
if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' && ($count = $product->get_review_count() ) )
printf( _n( '%s review for %s', '%s reviews for %s', $count,   'woocommerce' ), $count, get_the_title() );
else
_e( 'Reviews', 'woocommerce' );
?></h2>

为了做到这一点,我尝试使用以下内容,但它似乎不起作用。 我不确定我应该瞄准哪个字符串。

function lnz_replace_content()
{
echo str_replace("%s reviews for %s","%s comments about %s", $product);
}
add_filter('init','lnz_replace_content');'

我也尝试过gettext,但是在这种情况下也不起作用。

OP更新

我曾经尝试过使用gettext,但是在这种情况下似乎不起作用。

如前所述,我的目标是以下代码(在single-product-review.php中)

<h2><?php
if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' && ( $count = $product->get_review_count() ) )
printf( _n( '%s review for %s', '%s reviews for %s', $count, 'woocommerce' ), $count, get_the_title() );
else
_e( 'Reviews', 'woocommerce' );
?></h2>

如果我使用“ gettext”替换“评论”,则效果很好。 如果我尝试将其替换为“%s for%s”,则无法使用。

任何想法为什么。

您可以通过2种方法来做到这一点:

1)更改语言文件:

msgid "%s reviews for %s"
msgstr "%s comments about %s"

msgid "%s review for %s"
msgstr "%s comment about %s"

2)修改代码:

<h2><?php
if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' && ($count = $product->get_review_count() ) )
printf( _n( '%s review for %s', '%s reviews for %s', $count,   'woocommerce' ), $count, get_the_title() );
else
_e( 'Reviews', 'woocommerce' );
?></h2>

<h2><?php
if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' && ($count = $product->get_review_count() ) )
printf( _n( '%s comment about %s', '%s comment about %s', $count,   'woocommerce' ), $count, get_the_title() );
else
_e( 'Reviews', 'woocommerce' );
?></h2>

您可以使用模板替代来覆盖single-product-reviews.php是将其复制到主题的woocommerce文件夹中。

或者您可以从主题的functions.php过滤gettext

add_filter( 'gettext', 'theme_change_comment_field_names', 20, 3 );
/**
 * Change comment form default field names.
 *
 * @link http://codex.wordpress.org/Plugin_API/Filter_Reference/gettext
 */
function theme_change_comment_field_names( $translated_text, $text, $domain ) {

    if ( is_singular() ) {

        switch ( $translated_text ) {

            case '%s reviews for %s' :

                $translated_text = __( '%s comments for %s', 'theme_text_domain' );
                break;
           case 'Related Products' :
                $translated_text = __( 'Related Opportunities', 'theme_text_domain' );
                break;

        }

    }

    return $translated_text;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM