WordPress Coding Error: Non-sanitized input variables - php

I'm currently trying to keep to WordPress coding standards for an important exercise/job with an index page that loops through random posts, I'm using PHP Code Sniffer and getting this error:
Detected usage of a non-sanitized input variable: $_GET['my_posts_per_page']
Here is my code:
function my_random_posts() {
$my_posts_per_page = ! empty( wp_verify_nonce( $_GET['my_posts_per_page'] ) ) ? wp_verify_nonce( $_GET['my_posts_per_page'] ) : 10;
$randomised_posts = wp_get_random_posts( $number = $my_posts_per_page );
$output = '';
foreach ($randomised_posts as $randomised_post) {
$output .= '<li>';
$output .= '<h3>' . wptexturize( $randomised_post->post_title ) . '</h3>
<p>' . wptexturize( $randomised_post->post_content ) . '</p>
' . 'Read More' . '
</li>';
}
$output = '<ul class="randome_post">' . $output . '</ul>';
echo esc_html($output);
};
Also on the same line I'm getting this error:
Notice: Undefined index: my_posts_per_page
I've been scratching my head for hours here. Also, using the escape function on echo esc_html($output); now just brings all the code in (I know this is the purpose of the escaping function), though what's the point of this for Security when it shows the HTML without any embedded li, p, h3 tags, just the tag itself, for example:
<ul class="random_post"><li><h3>Hello world!</h3>
What do I do with the escaped HTML to get it to render correctly? And why am I getting an Undefined index?

For the actual post content, you might want to consider using WordPress function wp_kses_post( ), such as:
echo wp_kses_post( $content );
If it is just a small attribute for use within a tag, try using the WordPress function esc_attr( ), such as:
echo esc_attr( $attribute );
These will remove PHP code sniffer errors.

Related

Fatal error: Can't use method return value in write context in (word-press plugin)

I just installed a plugin to my word-press site and now I'm getting this message:
Fatal error: Can't use method return value in write context in /home2/royaldlx/public_html/wp-content/plugins/motopress-hotel-booking-lite/includes/admin/manage-cpt-pages/booking-manage-cpt-page.php on line 194
What had happened? is there any way to fix it? Thank you in advance.
Below the code:
if ( !empty( $customer->getEmail() ) ) {
$customerInfo .= '<br />'
. '<a href="mailto:' . esc_attr( $customer->getEmail() ) . '">'
. esc_html( $customer->getEmail() )
. '</a>';
}
There is two conflicts. Either you didnt install you wordpress right or your plugin is conflicted, try to change plugin or re-install wordpress.

Common php function called by other functions

Hello I would like to create two functions with different parameter but with a same common function. Here's my example...
The common function :
function my_responsive_pictures($post_id){
// Get alt text or set the $alt_text variable to the post title if no alt text exists
$alt_text = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
if ( !$alt_text ) { $alt_text = esc_html( get_the_title($post_id) ); }
// Get the info for each image size including the original (full)
$thumb_original = wp_get_attachment_image_src($attachment_id, 'slideshow');
$thumb_large = wp_get_attachment_image_src($attachment_id, 'slideshow-lg');
$thumb_medium = wp_get_attachment_image_src($attachment_id, 'slideshow-md');
$thumb_small = wp_get_attachment_image_src($attachment_id, 'slideshow-xs');
// Create array containing each image size + the alt tag
$thumb_data = array(
'thumb_original' => $thumb_original[0],
'thumb_large' => $thumb_large[0],
'thumb_medium' => $thumb_medium[0],
'thumb_small' => $thumb_small[0],
'thumb_alt' => $alt_text
);
// Echo out <picture> element based on code from above
echo '<picture>';
echo '<!--[if IE 9]><video style="display: none;"><![endif]-->'; // Fallback to <video> element for IE9
echo '<source srcset="' . $thumb_data['thumb_large'] . ', ' . $thumb_data['thumb_original'] . ' x2" media="(min-width: 800px)">';
echo '<source srcset="' . $thumb_data['thumb_medium'] . ', ' . $thumb_data['thumb_large'] . ' x2" media="(min-width: 400px)">';
echo '<source srcset="' . $thumb_data['thumb_small'] . ', ' . $thumb_data['thumb_medium'] . ' x2">';
echo '<!--[if IE 9]></video><![endif]-->'; // Fallback to <video> element for IE9
echo '<img srcset="' . $thumb_data['thumb_small'] . ', ' . $thumb_data['thumb_medium'] . ' x2" alt="' . $thumb_data['thumb_alt'] . '">';
echo '</picture>';
}
Another one which calls the common function :
function my_responsive_thumbnail($post_id){
// Get the featured image ID
$attachment_id = get_post_thumbnail_id($post_id);
my_responsive_pictures();
}
And a second one with other parameters $attachment_ID :
function my_responsive_acfthumbnail($post_id){
// Get the featured image ID
$attachment_id = get_field('image_bandeau');
my_responsive_pictures();
}
Nothing happens :(. What do I do wrong ? Thanx for your help...
Your function is expecting a parameter, and when you're calling it here
my_responsive_pictures();
you aren't passing anything.
You also have to call the my_responsive_thumbnail() function before it's going to make the subsequent calls to your "common" function.
There are a few issues with this code. The first thing we need to look at is the main function.
function my_responsive_pictures($post_id){
Your function definition doesn't give $post_id a default value therefore it's required any time you call the function. By attempting to call the function without passing an the argument you'll trigger an error.
$alt_text = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
if ( !$alt_text ) { $alt_text = esc_html( get_the_title($post_id) ); }
Here you're referring to $attachment_id which hasn't been set. When it's not found you're then getting the title of the post.
For this to work you'll need to set two parameters for the function.
function my_responsive_pictures( $attachment_id, $post_id ) {
Any time we call this function we need to pass in the $attachment_id (ID of the image) and $post_id (ID of the post).
Next up we need to modify the functions that ultimately call the main function.
function my_responsive_thumbnail( $post_id ) {
// Get the featured image ID
$attachment_id = get_post_thumbnail_id( $post_id );
// Now that we have the featured image ID, we really ought
// to do some error checking. Let's assume that all went well.
my_responsive_pictures( $attachment_id, $post_id );
}
This next function requires more attention. Remember that you're calling these functions with the post ID. You need to let get_field() know the ID of the post it should retrieve the image for.
function my_responsive_acfthumbnail( $post_id ) {
// Get the featured image ID
$attachment_id = get_field( 'image_bandeau', $post_id );
my_responsive_pictures( $attachment_id, $post_id );
}
Example usage:
my_responsive_acfthumbnail( get_the_ID() );
You may also want to consider setting a default for the post ID so you don't need to pass it in when retrieving an image for the current post you're viewing.
Finally, consider the level of duplication between the functions which call my_responsive_pictures. You'll want to check the attachment ID is valid so the functions are likely to become larger with only 1 line that's different.
Further information on get_field(): https://www.advancedcustomfields.com/resources/get_field/

buddy press profile link not going to correct place

I created a bp-custom.php and regrouped the menu items fine. But now i am trying to add a link to go to /site/members. It list all the members.
When i add it though it goes under the profile I am viewing. I am redirecting to a wordpress page if that helps. Or is there a better way to do this.
Ex :
http://website.com/log-in/members/username/members/
I want it to go just here
http://website.com/log-in/members/
I would love to learn how to just put a url and no slug but whatever works. I do not know why it keeps referencing that signed in /member/username. I have even tried parent url and that did not work. I might have been using parent url syntax wrong.
Here is the function
function mb_bp_profile_menu_posts() {
global $bp;
bp_core_new_nav_item(
array(
'name' => 'Members',
'slug' => 'members',
'position' => 60,
)
);
}
I know that i can create .htaccess for this. But I don't want to do it.
May i know what is the clean way (alternate way) to do this?
I have tried what the user said in comment below and found in bp-members-template this function. I then added the part in bold to add the link but that did not work. I am just adding a google link for testing only.
function bp_get_displayed_user_nav() {
global $bp;
foreach ( (array) $bp->bp_nav as $user_nav_item ) {
if ( empty( $user_nav_item['show_for_displayed_user'] ) && !bp_is_my_profile() )
continue;
$selected = '';
if ( bp_is_current_component( $user_nav_item['slug'] ) ) {
$selected = ' class="current selected"';
}
if ( bp_loggedin_user_domain() ) {
$link = str_replace( bp_loggedin_user_domain(), bp_displayed_user_domain(), $user_nav_item['link'] );
} else {
$link = trailingslashit( bp_displayed_user_domain() . $user_nav_item['link'] );
}
echo apply_filters_ref_array( 'bp_get_displayed_user_nav_' . $user_nav_item['css_id'], array( '<li id="' . $user_nav_item['css_id'] . '-personal-li" ' . $selected . '><a id="user-' . $user_nav_item['css_id'] . '" href="' . $link . '">' . $user_nav_item['name'] . '</a></li>', &$user_nav_item ) );
**echo "<a href='http://www.google.com'>Google</a>"; }**
}
The bp_core_new_nav_item function is used to add a link to the user's navigation which explains why you're seeing URLs like /members/username/members/ when clicking on the tab. I don't think bp_core_new_nav_item is the right approach here.
An alternative approach would be to replace the function in your theme template that outputs the navigation with your own custom menu.
See this article on the BP Template Hierarchy which shows you how you can set up your own templates:
http://codex.buddypress.org/themes/theme-compatibility-1-7/template-hierarchy/

PHP Mixing html and code

(Preamble: Am new to PHP, coming from a C# background where I am used to very clean code. Am currently working on my own Wordpress site which has a purchased theme.)
I have seen this type of code in a WordPress theme:
<img src="<?php echo esc_url( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" id="logo"/>
I find this very hard to read compared to the refactored:
<?php
echo '<a href="';
echo esc_url( home_url( '/' ) );
echo "><img src=";
echo esc_url( $logo );
echo " alt=";
echo esc_attr( get_bloginfo( 'name' ) );
echo '" id="logo"/></a>'
?>
But this is the easiest by far:
<?php
get_anchor($url, $imgsource, $alt, $id);
?>
get_anchor being a custom function that echos an anchor configured according to the parameters.
But surely I am not the first to think of this. Are there any existing libs that have a set of functions that return properly formatted html like in this example? Is there something I am missing?
I've written a function that returns a HTML tag based on the pure PHP output:
function tag($name, $attrs, $content) {
$res = '';
$res .= '<' . $name;
foreach($attrs as $key => $val)
$res .= ' ' . $key . '="' . $val . '"';
$res .= isset($content) ? '>' . $content . '</'.$name.'>' : ' />';
return $res;
}
$name is the tagname (e.g. a)
$attrs is a key, value array with attributes (e.g. array('href','http://google.com/'))
$content is the content / body of the tag (an other element or text)
Example basic use:
echo tag('a', array('href' => 'http://google.com/'),'Google');
Example nested use with multiple children:
echo tag('ul',array(),
tag('li',array(),'one') .
tag('li',array(),'two') .
tag('li',array(),'three')
);
I believe what you are looking for are templates like Smarty. They are the cleanest way to display information as code and view are completely separated.
However Wordpress do not use them, I don't know why actually, probably because most PHP programmers are not used to it.
Most of the PHP frameworks provide such libraries to out put html through parameterized functions, most of them are part of view layer if the framework follows MVC pattern.
but if you are not using any of the framework then you may use these libraries from here
PHP Pear Packages
And for building forms in particular see
HTML_QuickForm2

How to return a certain html tag in php

Sorry if this is a really stupid question. I am just starting to learn PHP and am probably jumping the gun a bit.
I am writing a very 'simple' wordpress plugin which has a custom post type and takes the content from it and returns it on the homepage with a shortcode. Below is the part of the code that handles the shortcode.
add_shortcode("new-tub", "new_tub_short");
function new_tub_short() {
$post_id = 87;
return '<a class="new-tub" href="' . home_url( '/test' , __FILE__ ) . '">' . get_post_field('post_content', $post_id) . '</a>';
}
So currently it wraps a link around the content of the post. All that is in the post will be an image, however, I would like to make it fool proof so it doesnt include another link and paragraph tag.
My question is, is it possible to search for the img tag within that post and return that only?
Thanks in advance,
Alex
You can do this by using strip_tags. Try this,
add_shortcode("new-tub", "new_tub_short");
function new_tub_short() {
$post_id = 87;
return '<a class="new-tub" href="' . home_url( '/test' , __FILE__ ) . '">' . strip_tags(get_post_field('post_content', $post_id), '<img>') . '</a>';
}
http://php.net/manual/en/function.strip-tags.php

Categories