WordPress.org

Ready to get started?Download WordPress

Forums

Dynamically Insert a Custom Field into a Shortcode (4 posts)

  1. Exponential
    Member
    Posted 6 months ago #

    Hi there,

    I am trying to dynamically insert a custom field (course ID) into a shortcode.

    The shortcode is as follows

    [learndash_payment_buttons course_id="INSERT"]

    I am using a custom field to insert course ID for each page and the usual way to call the custom field is:

    <?php getCustomField('Course ID'); ?>

    Does anyone know if it is possible to combine the two so I can dynamically call the course ID within the shortcode?

    I have tried a few approaches but nothing seems to work.

    Thanks in advance.

    James

  2. C W
    Member
    Posted 6 months ago #

    getCustomField() is not a native WordPress function and I don't know how it behaves. If I were using the in-built function get_post_meta() (function reference), I would most likely use it with do_shortcode() (function reference) as follows:

    <?php
       $value_cid = get_post_meta( get_the_ID(), 'the_custom_field_key', true );
       $shortcode_cid = '[learndash_payment_buttons course_id="' . $value_cid . '"]';
       echo do_shortcode( $shortcode_cid );
    ?>

    Where the_custom_field_key is the meta key whose value you want to retrieve.

    This getCustomField() function may produce analogous output to get_post_meta() or it may not. I don't know. To see if it does, you could start by trying to replace that first line with:

    $value_cid = getCustomField( 'Course ID' );
  3. Exponential
    Member
    Posted 6 months ago #

    Hi there, many thanks for your response! Much appreciated.

    I have tried what you suggested and the output is just the Course ID and it is not including the shortcode.

    Any suggestions?

  4. Exponential
    Member
    Posted 6 months ago #

    CRACKED IT! Thank you very much for your help!! :)

    <?php
    $courseID = get_post_meta($post->ID, "Course ID", true);
    $shortcode_cid = '[learndash_payment_buttons course_id="' . $courseID . '"]';
    if($shortcode_cid) echo do_shortcode( $shortcode_cid );
    ?>

Reply

You must log in to post.

About this Topic