1

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?

Thanks

2
  • 2
    Why can't you create a shortcode? What have you tried? What was the problem?
    – Milo
    Commented Jul 18, 2017 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 Commented Jul 18, 2017 at 13:12

1 Answer 1

1

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

add_shortcode('my-shortcode','my_shortcode_function');
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:

add_shortcode('my-shortcode','my_shortcode_function');
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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