I have the following if statement:
<?php
$title = esc_html( get_the_title() );
$sub_title = esc_html( get_field('sub_title') );
if ( get_field('sub_title') ) {
echo '<h1>'.$title.'</h1>';
echo '<h2>'.$sub_title.'</h2>';
}
else {
echo '<h1 class="nm">'.$title.'</h1>';
}
?>
Instead of this line:
<?php
if ( get_field('sub_title') ) {
echo '<h1>'.$title.'</h1>';
echo '<h2>'.$sub_title.'</h2>';
}
?>
I would like to use:
<?php
if ( $sub_title ) {
echo '<h1>'.$title.'</h1>';
echo '<h2>'.$sub_title.'</h2>';
}
?>
As the $sub_title variable has an escaped value, is it okay to use within an if statement?
As a manner of general principle, try to avoid using escaped data except at the point where you actually need the escapes. For instance, don't add HTML escaping until you get to the code that actually adds it to HTML. So I would write it as:
<?php
$title = esc_html( get_the_title() );
$sub_title = get_field('sub_title');
if ( $sub_title ) {
echo '<h1>'.$title.'</h1>';
echo '<h2>'.esc_html($sub_title).'</h2>';
}
else {
echo '<h1 class="nm">'.$title.'</h1>';
}
?>
In some cases, as in your code, it may not matter. Your if statement just cares whether the string is empty or not, and escaping an empty string doesn't add anything to it, so the result of the if will be the same.
But there are more complex cases where you might compare the string to another string, and depending on what you're comparing with it could change the result.
Similar advice applies when storing data in databases. Store the raw data, don't escape it then. Escape it after you retrieve it, when you're showing it on an HTML page. That way, when you perform queries that don't involve displaying the result in HTML (e.g. creating a CSV file, displaying in plain text, etc.), you don't have to contend with the escapes that might have been added.
Related
In a display of wordpress, I used the esc_html__() method to escape the string and add variables for safe use in HTML output.
My code is as follows:
<?php
global $product, $post;
$posts_id = $product->get_id();
$reserve_price = get_post_meta($posts_id, '_auction_reserved_price', true);
if ($product->is_reserved() === true && $product->is_reserve_met() === false) : ?>
<p class="reserve hold" data-auction-id="<?php echo esc_attr( $product->get_id() ); ?>">
<?php echo apply_filters('reserve_bid_text', esc_html__('Reserve price has not been met, needed to enter $ %s or more', 'wc_simple_auctions', $reserve_price)); ?>
</p>
<?php endif; ?>
But my variable is not output to the final value, the output string I get is this:
I tried before $reserve_price is a non-empty variable, but esc_html__() doesn't output the correct information to the page.
I am not quite sure about this reason.
"I tried before $reserve_price is a non-empty variable, but esc_html__() doesn't output the correct information to the page."
You can not use placeholders in esc_html__() function. It only retrieves the translation of a given text and escapes it for safe use in HTML output. Which means you could use it to:
Escape html markups + translation
However, if you would need to:
Escape html markups + translation + placeholder(s)
Then you could use the combination of esc_html, sprintf and __() functions, like so:
$test_value = '<strong>5.7<strong>';
echo esc_html(
sprintf(
__('This is a test for %s', 'your-text-domain'),
$test_value
)
)
Which will output this:
And if the provided text does not have any html tag(s), then it'd be something like this:
$test_value = 5.7;
echo esc_html(
sprintf(
__('This is a test for %s', 'your-text-domain'),
$test_value
)
)
Now, if we apply the same principles to your snippet, then it would be something like this:
<p class='reserve hold' data-auction-id='<?php echo esc_attr($product->get_id()); ?>'>
<?php
echo apply_filters(
'reserve_bid_text',
esc_html(
sprintf(
__('Reserve price has not been met, needed to enter $ %s or more', 'wc_simple_auctions'),
$reserve_price
)
)
);
?>
</p>
Let me know if you could get it to work!
I have the following piece of PHP code as part of my site theme. Where I am stuck is, if the value of $sec_title contains an apostrophe, then the text doesn't display. But without an apostrophe, it contains fine. How can I amend this to prevent this issue?
<?php
if ( $sec_title ) {
echo do_shortcode( "[onex_section_header
title={$sec_title}
subtitle='{$sec_subtitle}']"
);
} ?>
Try using:
$sec_title = addslashes($sec_title)
before you echo or try switching the double and single quotes around as so
echo do_shortcode('[onex_section_header
title={$sec_title}
subtitle="{$sec_subtitle}"]'
);
I'm trying to add a return policy custom field just above the add to cart button in woocommerce. I've got the following function:
<?php
add_action( 'woocommerce_single_product_summary', 'return_policy', 20 );
function return_policy() {
echo '<div id="return-policy-wrapper">
<?php the_cfc_field('rp-info-meta', 'rp-info-custom-filed'); ?>
</div>';
}
But the code validator points out there is an error somewhere in the string. I suspect the the error is with the single quote marks inside
<?php the_cfc_field('rp-info-meta', 'rp-info-custom-filed'); ?>
I changed the single quotes in that string for double quotes. Now the string validation error is gone, but the function won't work.
Are they the single quotes that are causing the error and how can I fix it?
You're already in a <?php ... ?> context. Simply build your string. For example
printf('<div id="return-policy-wrapper">%s</div>',
get_cfc_field('rp-info-meta', 'rp-info-custom-filed'));
or
echo '<div id="return-policy-wrapper">',
get_cfc_field('rp-info-meta', 'rp-info-custom-filed'),
'</div>';
Note, I've used get_cfc_field instead so the string is returned and not echo-ed directly.
Another approach would be
echo '<div id="return-policy-wrapper">';
the_cfc_field('rp-info-meta', 'rp-info-custom-filed'); // this echoes the value
echo '</div>'
The script is in the quoted string passed to the echo command, and is therefore not treated as a script, but echoed along with the rest of the string.
This might work as intended:
<?php
add_action('woocommerce_single_product_summary', 'return_policy', 20);
function return_policy() {
$info = get_cfc_field('rp-info-meta', 'rp-info-custom-field');
echo '<div id="return-policy-wrapper">';
echo $info;
echo '</div>';
}
?>
You can't use <?php inside another <?php [...] ?> block.
You code should be similar to that:
<?php
add_action( 'woocommerce_single_product_summary', 'return_policy', 20 );
function return_policy() {
echo '<div id="return-policy-wrapper">' . the_cfc_field('rp-info-meta', 'rp-info-custom-filed') . '</div>';
}
If you see carefully, HTML content is inside single quotes and never contains other single quoted characters (only double ones). Then, I concat the HTML text with the the_cfc_field() function that returns a string and then concat back with more html.
I'm a little lost here, hoping that someone can help. I'm using the Meta Box plugin for WordPress, and I'm trying to create a process for the user to select an option from a predefined list, and then assign a URL to that option as a link. Im trying to define the URL in a variable, and then call it in a function, but I'm still a little green on PHP syntax. this is my code now:
<?php
$article_url= rwmb_meta('orion_2016_article_url', 'type=URL');
if (rwmb_meta('orion_2016_article_source') != '') {
echo '<a href= ("$article_url") target=blank>';
echo rwmb_meta('orion_2016_article_source');
echo '</a>';} ?> on <?php the_date(); ?>
Since the options are already predefined, it seems like assigning a random URL to one of the options should be pretty simple. Hopefully this makes sense!
You need to to place variables you wish to echo inside double quotes or simply concatenate strings using . as in my example. Note that I didn't check the plugin's specific syntax, only general PHP syntax.
<?php
$article_url= rwmb_meta( 'orion_2016_article_url', 'type=URL' );
if (rwmb_meta('orion_2016_article_source') != '') {
echo '' . rwmb_meta( 'orion_2016_article_source' ); . '';
} ?> on <?php the_date(); ?>
I have built the following function to pick driver names out of a table and return them pre-fixed with an image & inside a hyperlink.
This works fine, except for one driver's surname has "van't" in it. An apostrophe!
My function won't work on this name with the apostrophe. I know normally it's possible to add a backslash if just typing in an echo or similar.
I have also tried surrounding the variables with wordpress' esc_attr__ , and a few similar 'google-stackoverflow' suggested tags.
For the life of me I can't get the string replace to carry out on this name though.
Does anybody have any other ideas how I should go about escaping the apostrophe when it is being called in from a variable?
This is my function - $profiletitle is the variable containing the stray 'apostrophe surname':
function replace_stuff($texto) {
if (is_front_page() || is_page('2611') || is_child('2611') || get_post_type() == 'drivers') {
query_posts('post_type=drivers');
if (\have_posts()) :
while (have_posts()) : the_post();
$profiletitle = get_the_title();
$profilenationality = get_custom_field('driver_nationality');
$profilelink = get_the_permalink();
$replace_magic[$profiletitle] = '' . do_shortcode($profilenationality) . '<span class="no_translate">' . $profiletitle . '</span>';
endwhile;
endif;
}
$textp = str_replace(array_keys( (array)$replace_magic), $replace_magic, $texto);
return $textp . wp_reset_query();
}
add_filter('tablepress_table_output', 'replace_stuff');
Many thanks!