I have written the following code with the goal of dynamically populating the woocommerce shortcode [product_page id="X"] with a url parameter where X is the product id, with a fallback default (product ID=46) if no parameter exists in the url.
For example:
example.com/somepage?ppid=60 would change the shortcode to [product_page id="60"]
whereas
example.com/somepage would change the shortcode to [product_page id="46"] where 46 is the "default"
However, it is currently not returning the correct product page. Oddly, no matter what I try, it defaults to product ID 440 (which is the highest product ID in my db).
function ppid_from_query($atts) {
$atts = shortcode_atts(array('default' => 46), $atts, 'myppid');
$pp_id = $atts['default'];
if (isset($_REQUEST['ppid']) && !empty($_REQUEST['ppid'])) {
$pp_id = intval($_REQUEST['ppid']);
}
if (!empty($pp_id) && 46 != $pp_id) {
return do_shortcode("[product_page id='{$ppid}']");
}
}
add_shortcode('myppid', 'ppid_from_query');
And shortcode is added to page like [myppid default=46"]
What am I doing wrong?
You pass the wrong variable $ppid
instead of $pp_id
. try below code.
function ppid_from_query( $atts ) {
$atts = shortcode_atts( array(
'default' => 46
), $atts, 'myppid' );
$pp_id = $atts['default'];
if ( isset( $_REQUEST['ppid'] ) && $_REQUEST['ppid'] != '' ) {
$pp_id = intval( $_REQUEST['ppid'] );
}
return do_shortcode( "[product_page id='".$pp_id."']" );
}
add_shortcode( 'myppid', 'ppid_from_query' );