1
function customfield_1_shortcode( $atts ) {

            if ( get_post_meta( get_the_ID(), 'customfield1', true ) ) {
        $customfield = get_post_meta( get_the_ID(), 'customfield1', true );

    return "html stuff";
}
add_shortcode( 'customfield_1', 'customfield_1_shortcode' );

function customfield_2_shortcode( $atts ) {

            if ( get_post_meta( get_the_ID(), 'customfield2', true ) ) {
        $customfield = get_post_meta( get_the_ID(), 'customfield2', true );

    return "html stuff";
}
add_shortcode( 'customfield_2', 'customfield_2_shortcode' );
?>

I can use [customfield_1] to output customfield1 stuff, and [customfield_2] to output customfield2. What is the best way to combine these two or more functions like these (customfield_3, customfield_4 etc.) to achieve the similar effect?

2

I don't know exactly what you are trying to do but perhaps something like this:

function customfields_shortcode( $atts ) {
  if (!empty($atts['field']) && get_post_meta( get_the_ID(), $atts['field'], true ) ) {
    $customfield = get_post_meta( get_the_ID(), $atts['field'], true );
    return "custom field >> $customfield << custom field";
  }
}
add_shortcode( 'mycustomfields', 'customfields_shortcode' );

echo do_shortcode('[mycustomfields field="customfield_1"]');

One shortcode will handle all of your custom fields. Just pass in the field you want as an attribute (argument).

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.