Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get post ID in variable in Grid Builder Visual Composer

I’m trying to get some custom fields inside my custom grid builder. I have added some extra taxonomy and would like to add custom data to display. I’ve read your article here: https://kb.wpbakery.com/docs/developers-how-tos/adding-custom-shortcode-to-grid-builder/ and when implementing it, I’m getting a problem when trying to get the id of the current post ID. I know the code is as follows:

add_shortcode( 'vc_post_id', 'vc_post_id_render' );
function vc_post_id_render() {
   return '<h2>{{ post_data:ID }}</h2>'; // usage of template variable post_data with argument "ID" 
}

The thing is that the {{ post_data:ID }} cannot be saved to a variable to later get the post and play with it as such:

$post_id = '{{ post_data:ID }}';
$post = get_post($post_id);

as it will fail. Could you please tell me how to get the current post ID as a variable so I can show custom data on the grid?

Thank you very much.

like image 382
Giovanni Ricciardi Avatar asked Apr 10 '17 09:04

Giovanni Ricciardi


2 Answers

Ok, here what I'm thinking. In my scenario, I have a custom field called price. So I was able to show the price by using

{{ post_data:price }}

This. But when I was trying to assign it to a variable, it failed. When I var_dump the variable it gives me (21) characters for every time. So I thought there must be invisible characters. so I

echo bin2hex($price)

The result was 7b7b20706f73745f646174613a7072696365207d7d

And after ASCII to text conversion, it became this

{{ post_data:price }}

Then I realized it. Oh silly me. These are template tags. Like in smarty or angular. They injected values once the page has loaded. So PHP doesn't have a chance get value because everything happening on the client side.

like image 80
amilaishere Avatar answered Nov 08 '22 12:11

amilaishere


you need to create vc_gitem_template_attribute_YOUR_ATTRIBUTE and there you can take id. like this:

add_filter( 'vc_gitem_template_attribute_producer_logo', 'vc_gitem_template_attribute_producer_logo', 10, 2 );
function vc_gitem_template_attribute_producer_logo( $value, $data ) {

  extract( array_merge( array(
   'post' => null,
   'data' => '',
  ), $data ) );

  $termini = get_the_terms( $post->ID, 'producer' );
  $logo = get_field('prlogo', $termini[0]);
  $image = '<img class="img-prod" src="' . $logo . '">';

  return $image;
} 

and render

add_shortcode( 'producer_logo', 'vc_producer_logo_render' );
function vc_producer_logo_render($atts, $content, $tag) {
    return '{{producer_logo}}';
}
like image 22
Виталий Капранов Avatar answered Nov 08 '22 14:11

Виталий Капранов