I am looking to create a dynamic Add-to-Cart button. The problem is that I need my server to dynamically create the "add-to-cart" URL.

Currently, I have a static example built here at this link.

You'll notice at the bottom of the page is a pay-per-post function, and an "Unlock Full Article" button. I would like this button to act as an add-to-cart button. The only problem I am having thus far, is how to dynamically create the correct URL extension?

Here is the static URL: https://example.com/insider/?add-to-cart=**2634**

That post ID needs to be dynamically created based on the page. I thought to try this:

https://example.com/insider/?add-to-cart=<?php echo the_ID(); ?> 

but it explicitly echoes this in-page.

Is there a way to customize this dynamically and use the_ID() function to get the id of each post this button is on?

1 Answer 1


There is almost never a scenario where executing PHP code entered from the wysiwyg editor is a good idea. It opens up a whole bunch of security issues.

The best way to achieve what you are looking for is to setup a custom short code that will return the link you are interested in. Add something like this to your functions.php file in your theme.

    function wpsc_my_special_cart_link(){
        return "https://diginomics.com/insider/?add-to-cart=" . get_the_ID();
    add_shortcode('my_special_cart_link', 'wpsc_my_special_cart_link');

Now, anywhere in your post you want that url to appear you can simply type [my_special_cart_link] and your php code will be executed and the string that the function returns will be displayed.

I'd recommend modifying this function so that it is able to do the whole thing for you. i.e. rather than just returning the url, have it return the whole button, something like

function wpsc_my_special_cart_link(){
    $url = "https://diginomics.com/insider/?add-to-cart=" . get_the_ID();
    return '<a class="button" href="' . $url . '">My Link Text</a>';
add_shortcode('my_special_cart_link', 'wpsc_my_special_cart_link');

One other thing to note, if you are linking to another page within your site, it is considered better practice to use home_url('path/to/subpage') rather than manually typing out the url for your site. In that scenario, the code would look like this:

    function wpsc_my_special_cart_link(){
        return home_url("insider/?add-to-cart=" . get_the_ID());
    add_shortcode('my_special_cart_link', 'wpsc_my_special_cart_link');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.