James14865
James14865

Reputation: 25

WooCommerce product shortcode not working in functions.php

I am working on wordpress shortcode. In the functions.php, I have added following code

add_shortcode('post-footer-note', 'getPostFooterNote');
function getPostFooterNote() {
    return "<div>Hope you find this tutorial useful! <a href='#'>Share this link</a> on Social Media.</div>";
}

and in the post page, I added [post-footer-note] The code works fine. Instead of "Hope you find this tutorial useful" text I want to display WooCommerce products. To show the products on the page, I made few changes in the code

add_shortcode('post-footer-note', 'getPostFooterNote');
function getPostFooterNote() {
    return "<div>[products limit="8" columns="4" category="hoodies, tshirts" cat_operator="NOT IN"]</div>";
}

After making changes, following error is showing.

Your PHP code changes were rolled back due to an error on line 461 of file C:\xampp\htdocs\wordpress\wp-content\themes\twentynineteen\functions.php. Please fix and try saving again.

syntax error, unexpected integer "8", expecting ";"

Upvotes: 0

Views: 415

Answers (1)

M H
M H

Reputation: 567

You have a syntax error in:

function getPostFooterNote() {
    return "<div>[products limit="8" columns="4" category="hoodies, tshirts" 
cat_operator="NOT IN"]</div>";
}

You need to use different quotations like this:

function getPostFooterNote() {
    return do_shortcode("<div>[products limit='8' columns='4' category='hoodies,  tshirts' cat_operator='NOT IN']</div>");
}

You could also flip the quotes (it doesn't matter which is the outer quotation marks (double or single).

As per the error, the second double quote is just before the 8, and therefore the return is concluded, and a semicolon is expected. Instead 8 is next, and the compiler doesn't know how to parse your code.

Edit: added @Moshe Gross' edit to final solution.

Upvotes: 3

Related Questions