How to show a “Buy Now” link button below posts using Advanced Custom Fields in Genesis

Posted on
5/5 - (402 votes)

This tutorial provides the code to output a “Buy Now” link button below entry content in Genesis if a affiliate_product_url custom field created using Advanced Custom Fields plugin is not empty.

We shall ensure that the link will be shown only if Affiliate Product URL has been entered for the individual posts.

Step 1

Install and activate Advanced Custom Fields.

It is recommended to use the Pro version since the free version of the plugin does not have a URL type field.

We shall use the free version in this tutorial.

Step 2

Create a field group named say, “Post Meta” having a “Affiliate Product URL” text field like so:

Step 3

Add the following in child theme’s functions.php:

add_action( 'genesis_after_entry_content', 'sk_show_affiliate_url' );
/**
 * Outputs a "Buy Now" link button below entry content if `affiliate_product_url` custom field is not empty.
 */
function sk_show_affiliate_url() {
    $affiliate_product_url = get_post_meta( get_the_ID(), 'affiliate_product_url', true );

    if ( $affiliate_product_url ) {
        printf( '<a href="%s" class="buy-now button">Buy Now</a>',
            esc_url( $affiliate_product_url )
        );
    }
}

Step 4

Add the following in child theme’s style.css:

.buy-now.button {
    margin-bottom: 28px;
}

Step 5

Add/Edit your Post(s), scroll down to “Page Meta” metabox and enter your desired external URL for that Post.