douxiluan6555 2018-07-21 13:41
浏览 42
已采纳

如何在Widget类中创建类

Let me first show you a demo that you can use and see the problem for yourself:

WidgetClass

class TestDemo_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            false,
            __( 'TestDemo' ),
            [ 'description' => __( 'A module to display an event', 'demo' ) ] );
    }

    public function form( $instance ) {
    ?>
      <p>
        <!--get_field_id generates and ID for us to use in the update method-->
        <label for="<?= $this->get_field_id( 'test' ); ?>">login text</label>
        <input class="widefat" id="<?= $this->get_field_id( 'test' ); ?>"
               name="<?= $this->get_field_name( 'test' ); ?>" type="text"
               value="<?= esc_attr( $instance['test'] ) ?>" data-default-color="#FFF"/>
      </p>
    <?php
    }

    public function update( $new_instance, $old_instance ) {
        $instance         = $old_instance;
        $instance['test'] = $new_instance['test'];

        return $instance;
    }


    public function widget( $args, $instance ) {
        $testObj = new Test();

        echo "WIDGETS LOADED " $testObj->testParameter;
        // expected result = "WIDGETS LOADED test successful"
    }
}

Demo (Model) Class

class Test {

    private $testParameter;

    public function __construct() {
        $this->testParameter = "test successful";
    }

    public function getTestParameter() {
        return $this->testParameter;
    }

    public function setTestParameter( $testParameter) {
        $this->testParameter= $testParameter;
    }

}

The above code doesn't give me an error, but it doesn't show the widget and also removes the admin bar at the top. My question would be: How can I call a new Class inside a widget?

I tried adding a parameter inside the TestDemo_Widget and adding a object inside that parameter when update function is called. This didn't work.

I also tried adding the Object to the $instance['customname'] = new Test(); inside the update function, but this also didn't work;

The ultimate goal is to make use of models inside the widget class.

  • 写回答

2条回答 默认 最新

  • doujiangqu2823 2018-07-23 16:23
    关注

    So after adding $this->loader->add_action( 'plugins_loaded', $plugin_admin, 'Test' ); and adding the dependency like require_once plugin_dir_path( dirname( __FILE__ ) ) . 'widgets/models/Test.php'; I made it work. I believe a better explanation for fixing this problem can be found here: https://wordpress.stackexchange.com/a/70060.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口