如何将动态数据传递给content_template方法-Elementor小部件开发?

问题描述 投票:0回答:1

在我的小部件类的

render()
方法中,我可以轻松查询帖子数据并按以下代码渲染,并且它正确显示在前端。


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; 
      
}

但是,这些帖子不会显示在 Elementor 编辑器页面中。 我尝试在

content_template
方法中访问帖子数据,但它不起作用。 那么,如何将帖子数据传递给
content_template
方法并渲染它?


protected function content_template(){
?>

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

<?php }

wordpress widget elementor
1个回答
0
投票

我找到了你的帖子,因为今天晚上我也遇到了同样的问题。解决方案非常简单。 我删除了 content_template() 函数。就是这样。 然后由 render() 函数生成预览。我不必使用循环,但我需要其他 WordPress 函数,例如 get_the_excerpt(Id)。此代码也在预览中运行。

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
}

我也应该测试一个循环,但已经晚了,如果我现在不回答,我永远不会这样做。

© www.soinside.com 2019 - 2024. All rights reserved.