1

in my ad site I was trying to create shortcode of some custom fields I created on a custom post type.

I'll explain

In the single post, there are the custom fields and are shown in a standard way in a table below.

If I want to take 1 of those custom filed, and add a shortcode to it and then show that custom filed easily where I want via the shortcode, how do you do it?

I hope I explained myself. I'm sure it's possible, but I can not try it for days.

I do not use the ACF plugin so I have to do it without this plugin, because everything is already set up in a plugin, not in the theme.

0

You’ll have to use add_shortcode to achieve this. Let’s say that you want this shortcode to be called “my_cf”:

function my_cf_shortcode_callback( $atts ) {
    $atts = shortcode_atts( array(
        'post_id' => get_the_ID(),
    ), $atts, 'my_cf' );

    return get_post_meta( $atts['post_id'], <FIELD_NAME>, true );
}
add_shortcode( 'my_cf', 'my_cf_shortcode_callback' );

Now you can use it by putting [my_cf] or [my_cf post_id=POST_ID] to your posts.

  • Do I have to copy the code to function.php? enter the name of the custom field and the name of the shortcode. At that point I can go for example on elementor, add the shortcode on the single ad, personalizing it and you will see the custom field in a dynamic way? For example, if this custom field that interests me, talk about colors. In each post I set a different color in a post there is written "green color" in another post "orange" so the custom field will show dynamically even with the shortcode? – antonio maraucci Feb 2 at 18:44
  • Yes - you should paste that code to your functions.php. And you have to change <FIELD_NAME> to real name of your custom field. Of course you can also change name of shortcode to whatever you like by replacing my_cf. – Krzysiek Dróżdż Feb 2 at 18:47
  • iI try but wordpress give me error, no save. Why – antonio maraucci Feb 2 at 18:48
  • is not this the code? add_shortcode( "sinle_post", function( $args ) { ob_start(); if( isset( $args["post_id"] ) ) { $post_id = $args["post_id"]; } else { $post_id = get_the_ID(); } – antonio maraucci Feb 2 at 18:50
  • What error do you get? – Krzysiek Dróżdż Feb 2 at 18:51

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.