ronaldtgi
ronaldtgi

Reputation: 727

How to pass dynamic data to content_template method - Elementor widget development?

In a render() method of my widget class, I can easily query the posts data and render as below code and it shows up at frontend correctly.


protected function render(){
 $args =  [
            'order'          => 'DESC',
            'posts_per_page' => 4
        ];

        $query = new \WP_Query($args);
        $posts = $query->posts;

        foreach($posts as $post) : ?>

             // loop the post here

        <?php endforeach; 
      
}

However, the posts doesn't show up in Elementor editor page. I try to access posts data inside content_template method and it doesn't work. So, how can I pass the posts data to content_template method and render it?


protected function content_template(){
?>

      <# _.each( settings.posts, function( post ) { #>
          <!-- loop the post here -->
      <# } #>

<?php }

Upvotes: 1

Views: 945

Answers (2)

slawek
slawek

Reputation: 111

protected function content_template() { return null; }

Instead of hiding it, you can also return null.

Upvotes: 1

Andy Paka
Andy Paka

Reputation: 96

I found your post, because I had the same problem this evening. The solution was ridiculous easy.

I removed my content_template() function. That's it.

The preview was then generated by the render() function. I don't have to use the loop, but I need other WordPress functions like get_the_excerpt(Id). This code runs in the preview as well.

protected function render() {
    $settings = $this->get_settings_for_display();

    if ( empty( $settings['post_id'] ) ) {
        return;
    }
    $excerpt = get_the_excerpt($settings['post_id']) ;
    $featuredImage = get_the_post_thumbnail($settings['post_id']) ;
    ?>
    <h3>
        <?php echo $settings['post_id']; ?>
    </h3>
    <div><?php echo $featuredImage ?></div>
    <div><?php echo $excerpt ?></div>
    <?php
}

I should have tested a loop as well, but it's really late, and if I don't answer now, I will never do.

Upvotes: 3

Related Questions