php - WordPress Coding Error: Non-sanitized input variables

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>
<a href="' . get_permalink($randomised_post->ID) . '" title="' . esc_attr(wptexturize($randomised_post->post_title)) . '">' . 'Read More' . '</a>
</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 onecho 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?
Answer
Solution:
For the actual post content, you might want to consider using WordPress functionwp_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 functionesc_attr( )
, such as:
echo esc_attr( $attribute );
These will remove PHP code sniffer errors.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: mark bundle as not supporting multiuse
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.