I'm working with visual composer and custom fields. i have the code for insert direct in PHP, but i can't create shortcode for this.

<div id="search-nacionalidad"><p class="<?php the_field('nacionalidad'); ?> noselect" title="<?php the_field('nacionalidad'); ?>" alt="<?php the_field('nacionalidad'); ?>"><?php the_field('nacionalidad'); ?></p></div>

How can I write a shortcode for this?


  • 2
    Why can't you create a shortcode? What have you tried? What was the problem? – Milo Jul 18 '17 at 12:38
  • 1
    @Milo Hi and thanks for ask. The problem is i'm creating a grid template. I have a custom field with all countries, and i want show flag, not text. I want change for example, SPAIN with flag image. The code works, but i need insert in visual composer, and only i can do it with shortcode – Vektor Unbreakable Jul 18 '17 at 13:12

Creating a shortcode is fairly simple, it only needs a shortcode name and maybe some arguments. Here is a simple one for you:

function my_shortcode_function(){ 
    return '<div id="search-nacionalidad"><p class="'. get_field('nacionalidad').' noselect" title="'.get_field('nacionalidad').'" alt="'. get_field('nacionalidad').'">'.get_field('nacionalidad').'</p></div>';

Now, using [my-shortcode] exactly does what your code does. However I'm not sure how do you use this, whether in a loop or not. If you need to pass the post's ID too, you need to use attributes. Take a look at this:

function my_shortcode_function($atts){ 
    $atts = shortcode_atts( array(
        'id' => '0',
    ), $atts, 'my-shortcode' );
    $id = $atts['id'];
    return '<div id="search-nacionalidad"><p class="'. get_the_field('nacionalidad',$id).' noselect" title="'.get_the_field('nacionalidad',$id).'" alt="'. get_the_field('nacionalidad',$id).'">'.get_the_field('nacionalidad',$id).'</p></div>';

Now if you use [my-shortcode id="123"] it will execute the code for the post that has an ID of 123. If no ID is provided, a default ID of 0 will be used instead.

| improve this answer | |

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.