I am in the process of setting up WordPress with WooCommerce, one of the requirements is a bit of integration that takes a person from another website directly to a specific product. I have set the external product references on tags in the products
an example incoming query would be:
http://localhost/TestSite/search?q=9404
I have written a short plugin that does this, but I can’t seem to get it to search products by tag.
You can see the two lines of $params for example, the top one (currently commented out) works fine when searching by product id, but the bottom one trying to work from tag produces nothing. Can you see where I am going wrong?
P.S. This is my first attempt at a wordpress plugin. it is potentially inefficient, security compromising or has some glaring issue. I am going to submit it to stack overflow code review, but I need to get this one last bug ironed out!
Thanks for any help you can offer. Also, if you can suggest an alternative method to getting from a tag to a product URL I will interested.
//Test Product Id: 11030
//Tag on Test Product: 9404
//http://localhost/TestSite/search?q=9404
function TagLinker() {
if (isset($_GET['q']))
{
$TagNumber = $_GET['q'];
//create the params array
//$params = array('post_type' => 'product', 'p' => 11030);
$params = array('post_type' => 'product', 'tag' => $TagNumber);
$wc_query = new WP_Query($params);
if ($wc_query -> have_posts() ) {
$wc_query -> the_post();
$product_id = get_the_ID();
$url = get_permalink( $product_id );
wp_reset_postdata();
if ( wp_redirect( $url ) ) {exit;}
};
}
}
add_action( 'init', 'TagLinker' );
3
Answers
Please try this:
You should give the tag in array. Kindly refer tag section in the developer page . https://developer.wordpress.org/reference/classes/wp_query/
try this code. It was working in my machine.