geoplous geoplous - 17 days ago 6
PHP Question

PHP accept any number

I have this code inside my posts:

[quick_view product_id="10289" type="button" label="Quick View"]


and I want to have inside a function the number "10289" matching any number:

if (stripos($post-> post_content, '[quick_view product_id="XXXX" type="button" label="Quick View"]') !== false)


How can replace the "XXXX" to accept all numbers?

Full snippet:

function conditionally_add_scripts_and_styles($posts){
if (empty($posts)) return $posts;
$shortcode_found = false; // use this flag to see if styles and scripts need to be enqueued
foreach ($posts as $post) {
if (stripos($post-> post_content, '[quick_view product_id="XXXX" type="button" label="Quick View"]') !== false) {
$shortcode_found = true; // bingo!
break;
}
}
if ($shortcode_found) {
// enqueue here
wp_enqueue_style('my-style', '/woocommerce.css');
wp_enqueue_script('my-script', '/script.js');
}
return $posts;
}


Thank you.

Answer

Try this, Hope it will work fine.

Regex: /product_id\s*\=\s*\"\d+\"/ This regular expression will look for digits in between product_id="<->"

Examples:

product_id="xxAbcxx" will be rejected.

product_id="1212121" will be accepted.

if(preg_match("/product_id\s*\=\s*\"\d+\"/", $post->post_content))
{
    echo "Accepted";   
}

Your complete code will look like this.

function conditionally_add_scripts_and_styles($posts)
{
    if (empty($posts))
        return $posts;
    $shortcode_found = false; // use this flag to see if styles and scripts   need to be enqueued
    foreach ($posts as $post)
    {
        if(preg_match("/product_id\s*\=\s*\"\d+\"/", $post->post_content))
        {
            $shortcode_found = true;   
            break;
        }
    }
    if ($shortcode_found)
    {
// enqueue here
        wp_enqueue_style('my-style', '/woocommerce.css');
        wp_enqueue_script('my-script', '/script.js');
    }
    return $posts;
}