Support

Account

Home Forums General Issues Bring value from ACF into WP Function

Solved

Bring value from ACF into WP Function

  • I’m trying to build a wordpress function that displays a link to eBay or other sites, populating the link with details from an ACF field.

    This is the current code. I’m adding this code to a Generatepress Element that is basically a custom post type template that displays information about a trading card from the ACF fields.

    It’s doing that part great, I’m just having trouble getting the acf data to pull and display in the link part.

    Do I need to get the card ID based on the current post ID possibly?

    function buy_card_shortcode() {
        $card_details = get_field('card_id');
    
        $output = '<a class="buy-card-class" href="https://www.ebay.com/sch/i.html?_nkw= . $card_details . ">eBay</a>';
        return $output;
    }
    add_shortcode( 'buy_card', 'buy_card_shortcode' );

    The output in HTML is

    <a href="https://www.ebay.com/sch/i.html?_nkw= . $card_details .">eBay</a>

  • Yes, you need the post ID so you could add a global $post to reference the post object so something like:

    function buy_card_shortcode() {
        global $post;
        $card_details = get_field('card_id');
    
        $output = '<a class="buy-card-class" href="https://www.ebay.com/sch/i.html?_nkw='. $card_details .'">eBay</a>';
        return $output;
    }
    add_shortcode( 'buy_card', 'buy_card_shortcode' );

    I did adjust your output as I think there was an error there around where the variable was referenced, as well.

  • Thanks! Super helpful 🙂

    I’ve slightly updated the code and I’ll leave it here in case it helps anyone googling for stuff like adding two ACF fields together, dynamic link from ACF fields e.t.c

    function buy_card_shortcode() {
    	global $post;
        $card_id = get_field('card_id');
    	$card_name = preg_replace('/\s+/', '+', get_field('card_name'));
        $output = '<a class="buy-card" href="https://www.ebay.com/sch/i.html?_nkw='.$card_id. '+' .$card_name.'">eBay</a>';
        return $output;
    
    }
    add_shortcode( 'buy_card', 'buy_card_shortcode' );

    This code gets the post id, then gets one text field, then gets another and replaces all spaces and whitespace in that second text field with the + symbol.

    It then prints a link to ebay with both fields added together, with the plus symbol in the middle because that’s how eBay handles spaces.

    Then you just put the shortcode [buy_card] into any post and it’ll print a link saying “eBay” that links to a search for that card (or whatever you use) on eBay. You can then add an affiliate link on the text, something I’ll eventually do.

    There is a CSS class called “buy-card” that you can then style the link with.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.