How to change text (strings) in Wordpress plugins - php

Frequently I need to change specific bits of text within Wordpress plugins, usually buttons and usually set within the plugin files as strings.
Sometimes an overide within my child theme does the trick but in most cases seems like overkill to change one or two words. I've had some success using the 'gettext' hook, but it has been suggested this is bad practice as I'm 'pushing content through the eye of a needle'.
In the example below I'm able to change the text for two buttons specifically within the Memberpress plugin. It seems to work okay but is there a better way of doing this?
function mepr_account_strings( $translated_text, $text, $domain ) {
switch ( $translated_text ) {
case 'Update' :
$translated_text = __( 'Update Card', 'memberpress' );
break;
case 'Cancel' :
$translated_text = __( 'Cancel Subscription', 'memberpress' );
break;
}
return $translated_text;
}
add_filter( 'gettext', 'mepr_account_strings', 20, 3 );

Related

How to add HTML in "No products were found matching your selection" WooCommerce message

In WooCommerce, The "No products were found matching your selection." text appears when no products are found in the loop.
However, I want to add HTML in the text, so I use the gettext filter hook. Via str_ireplace I can easily overwrite the text:
function change_empty_category_text($translated) {
$translated = str_ireplace ('No products were found matching your selection.', 'sorry! we are not delivering products from this category to you pin code at the moment.', $translated);
return $translated;
}
add_filter( 'gettext', 'change_empty_category_text' );
However, when I want to add HTML in this text:
function change_empty_category_text($translated) {
$translated = str_ireplace ('No products were found matching your selection.', 'sorry! we are not delivering products from this category to you pin code at the moment.\r\nplease visit the following categories instead\r\n<a href = 'www.example.com/category1'>category 1</a>\r\n<a href = 'www.example.com/category2'>category 2</a>\r\n<a href = 'www.example.com/category3'>category 3</a>', $translated);
return $translated;
}
add_filter( 'gettext', 'change_empty_category_text' );
It has no result. Instead, I am getting the same exact text as written in the replacement.
Any advice?
The text you want to adjust can be found in templates/loop/no-products-found.php, so you could overwrite the template file
versus using the gettext filter hook, since this hook is executed multiple times on every page load.
However, there is another option. Since wc_no_products_found uses function_exits, see: /includes/wc-template-functions.php on line 3254-3262 #version 2.5.0
if ( ! function_exists( 'wc_no_products_found' ) ) {
/**
* Handles the loop when no products were found/no product exist.
*/
function wc_no_products_found() {
wc_get_template( 'loop/no-products-found.php' );
}
}
More info: What's "function_exists" in Wordpress
So instead of using the existing template file, which is called via wc_get_template() in the function, we are going to rewrite the function with our own function.
So you get:
function wc_no_products_found() {
echo '<p class="woocommerce-info" style="display:block;">' .
__( 'Sorry! we are not delivering products from this category to you pin code at the moment.<br>Please visit the following categories instead', 'woocommerce' )
. '<br>category 2<br>category 3</p>';
}
As you can see the output is fully customizable to your needs. CSS adjustments may be required, since this is theme dependent.
Code goes in functions.php file of your active child theme (or active theme).

Make changeable text field translate ready in php

I have a text field in the backend. The text value inside it will be different depends on the products I choose. So, it's a kind of dynamic field.
How can I target that field to make it translatable?
so each time I create an offer WPML can detect the string?
if ( $total_to_add - $total_added > 0 ) {
if ( ! in_array( $rule['key'], $special_offers, true ) ) {
$rule_text = isset( $rule['text_in_modal_special_offer'] ) ? $rule['text_in_modal_special_offer'] : __( 'Get a special discount if you add {{total_to_add}} product(s) to your order.', 'discountText' );
$special_offer = array(
'text' => $rule_text,
'items_in_cart' => $total_added,
'discount' => array(
'type' => $discount['discount_amount']['type'],
'amount' => $discount['discount_amount']['amount'],
),
);
$special_offers[ $rule['key'] ] = $special_offer;
}
}
You need to use the "Auto-register strings for translation" feature of WPML (documentation):
WPML uses static code analysis to locate strings that require translation in the theme and plugins. In some cases, the static code-scan cannot reliably find all strings. This often happens when strings are generated dynamically using code.
Then you need to go to the front end of the site and make sure both variants of your IF statement are executed. Also, I would try to __() the dynamic value as well:
$rule_text = isset( $rule['text_in_modal_special_offer'] ) ? __($rule['text_in_modal_special_offer'], 'discountText') : __( 'Get a special discount if you add {{total_to_add}} product(s) to your order.', 'discountText' );
After that, go to WPML > String Translation, search for both strings, and translate them.

Rename "Have A Promotional Code?" in Woocommerce

check please: http://www.baroniarialb.cat/finalitza-la-compra/
I have AVADA and Woocommerce theme installed, but I need to change the "Have A Promotional Code?" and I can't find the correct code to do it.
I have already tried different ways that appear on the internet without success from funtions.php.
Could you guide me?
Try this code. I've tested from the my side and it's working fine
function woocommerce_rename_coupon_field_on_cart( $translated_text, $text, $text_domain ) {
if ( is_admin() || 'woocommerce' !== $text_domain ) {
return $translated_text;
}
if ( 'Apply Coupon' === $text ) {
$translated_text = 'Put your text here'; //Here add your text which you want to replace
}
return $translated_text;
}
add_filter( 'changetext', 'woocommerce_rename_coupon_field_on_cart', 10, 3 );
You can change via jQuery also. Add the script in the footer.php file
<script>
jQuery("h2.promo-code-heading").text("Hello world!");
</script>
For strings translations on plugins, we use the locotranslate plugin, simple, fast and can use translated files for more wordpress instances.

Translate custom labels fields in function.php file of my theme

With the help from the community, I have succeeded to create, save and print the labels and their values to the single product page.
I can also translate the input values into different languages using Polylang, but translating the custom labels (Conditions and Brands) is extremely hard.
Anyone out there can help me with these issues?
I tried to use Polylang, Saywhat...with no success!
Here is the code:
// Enabling and Displaying Fields in backend
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_text_input( array( // Text Field type
'id' => '_conditions',
'label' => __( 'Conditions', 'woocommerce' ),
'placeholder' => 'i.e: brand-new; refurbished; defected...',
'desc_tip' => 'true',
'description' => __( 'Enter the conditions of the products here.', 'woocommerce' )
) );
woocommerce_wp_text_input( array( // Text Field type
'id' => '_brands',
'label' => __( 'Brands', 'woocommerce' ),
'placeholder' => 'i.e: Lacoste; Hugo Boss...etc',
'desc_tip' => 'true',
'description' => __( 'Enter names of the Brands of the products if any.', 'woocommerce' )
));
echo '</div>'; // Closing </div> tag HERE
}
// Save Fields values to database when submitted (Backend)
add_action( 'woocommerce_process_product_meta', 'woo_save_custom_general_fields' );
function woo_save_custom_general_fields( $post_id ){
// Saving "Conditions" field key/value
$conditions_field = $_POST['_conditions'];
if( !empty( $conditions_field ) )
update_post_meta( $post_id, '_conditions', esc_attr( $conditions_field ) );
// Saving "Brands" field key/value
$brands_field = $_POST['_brands'];
if( !empty( $brands_field ) )
update_post_meta( $post_id, '_brands', esc_attr( $brands_field ) );
}
add_action('woocommerce_single_product_summary', 'woo_display_custom_general_fields_values', 20);
function woo_display_custom_general_fields_values() {
global $product;
echo '<p class="custom-conditions">Conditions: ' . get_post_meta( $product->id, '_conditions', true ) . '</p>';
echo '<p class="custom-brands">Brands: ' . get_post_meta( $product->id, '_brands', true ) . '</p>';
}
And here a screenshot:
Thank you.
First, you should change the gettex domain name from 'woocommerce' to the domain name of your theme (or something more custom), as it doesn't make part of woocommerce code, and it's located in your active theme.
1) the Free alternative:
Then as it's not really content that you are trying to translate, but some peaces of code located in the function.php file of your active child theme (or active theme), you should use a specialized free plugin as Loco Translate that will provides in-browser editing of WordPress translation files.
Loco Translate, also provides localization tools for developers, such as extracting strings and generating templates.
Loco Translate features include:
Built-in translation editor within WordPress admin
Create and update language files directly in your theme or plugin
Extraction of translatable strings from your source code
Native MO file compilation without the need for Gettext on your system
Support for PO features including comments, references and plural forms
PO source view with clickable source code references
Protected language directory for saving custom translations
Configurable PO file backups
Built-in WordPress locale codes
2) The commercial complete way (completely compatible with WooCommerce):
The most complete commercial alternative is WPML plugin, that will also handle perfectly and more easily WooCommerce custom localisation and translations content for multilingual web sites. The other free optional plugins are incomplete for WooCommerce and much more difficult to get them work totally well.
So If you are planing to publish a multilingual website, think about it.

Add login form shortcode programatically to every published product page

I am running a wholesale shop on Woocommerce. Login is required to see the prices. This is set up and working properly. Now I wish to add a logon form on every product page to only show to visitors (not logged on users).
I am using the WooCommerce Catalog Visibility plugin. This plugin offers the functionality I described above, but my theme is somehow messing it up. The plugin author says to talk to the theme developer and the theme developer says to talk to the plugin author. So now I am trying to find a workaround.
First issue: The plugin comes with a shortcode [woocommerce_logon_form] that will display a logon form. I don't want to manually add this to every existing product since I have thousands of products on my site. I am looking for a way to get it in through the code for the product page layout.
I found this code (to be added to the functions.php) to work well:
// adds notice at single product page above add to cart
add_action( 'woocommerce_single_product_summary', 'return_policy', 20 );
function return_policy() {
echo '<p id="rtrn">30-day return policy offered. See Terms and Conditions for details.</p>';
}
However, it will only show text. The short code won't work when added instead of the sample text.
Second issue: The short code shows the form even when the customer is already logged in.
I am currently using this nice code that shows or hides content depending on whether the user is logged in or not:
add_shortcode( 'access', 'access_check_shortcode' );
function access_check_shortcode( $attr, $content = null ) {
extract( shortcode_atts( array( 'capability' => 'read' ), $attr ) );
if ( current_user_can( $capability ) && !is_null( $content ) && !is_feed() )
return $content;
return '';
}
add_shortcode( 'visitor', 'visitor_check_shortcode' );
function visitor_check_shortcode( $atts, $content = null ) {
if ( ( !is_user_logged_in() && !is_null( $content ) ) || is_feed() )
return $content;
return '';
}
That shortcode works perfectly for text, but not with other shortcodes.
So the combination of these short codes: [visitor][woocommerce_logon_form][/visitor] will not show the logon form to visitors. Instead it will only show them this as text [woocommerce_logon_form].
Please help! I am sure this is probably easily fixed by someone with coding skills.
I appreciate your effort to answer to this question. Keep in mind that my understanding of code is very limited and it would be great if you can also point out in which file to add or modify code.
To make your shortcode working in php code or in php/html code you need to use a native WordPress function do_shortcode() … You can use it with your shortcode for example in your 1st function this way:
add_action( 'woocommerce_single_product_summary', 'return_policy', 20 );
function return_policy() {
echo do_shortcode('[woocommerce_logon_form]');
}
And this will work…
To see all the different hooks you can use instead of woocommerce_single_product_summary, please see this 2 templates code to chose in case a more convenient hook:
WooCommerce single-product.php template
WooCommerce content-single-product.php template
You can also add it the same way in one of your existing short codes, this way:
add_shortcode( 'visitor', 'visitor_check_shortcode' );
function visitor_check_shortcode( $atts, $content = null ) {
if ( ( !is_user_logged_in() && !is_null( $content ) ) || is_feed() )
return do_shortcode('[woocommerce_logon_form]');
return '';
}
And this will work too.
See as reference this answer: Change markup in WooCommerce shortcode output
So as you can see your problem is solved on both issues

Categories