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

  1. Exponential
    Posted 2 years 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.


  2. C W (VYSO)
    Posted 2 years 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:

       $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
    Posted 2 years 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
    Posted 2 years ago #

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

    $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 );

Topic Closed

This topic has been closed to new replies.

About this Topic