워드프레스/위젯

위젯 클래스 예제 1

janggos 2024. 6. 13. 21:40

namespace wamp\widget;

if ( ! defined( 'ABSPATH' ) ) {
    exit( 'Go away!' );
}

class Wamp_Widget extends \WP_Widget {

    function __construct() {
        $widget_options = array(
            'classname' => 'WAMP-Widget',
            'description' => 'Just adds a simple widget box.'
        );
        parent::__construct( 'standard_Widget', 'My WAMP Widget', $widget_options );

        add_action( 'widgets_init', function () {
            register_widget( __NAMESPACE__.'\Wamp_Widget' );
        });

        add_action( 'wp_enqueue_scripts', array($this, 'widget_enqueue_styles' ));
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_admin_scripts' ));
    }

    function form( $instance ) {
        $title = ! empty( $instance['title'] ) ? $instance['title'] : 'Widget Title';
        $company = ! empty( $instance['company'] ) ? $instance['company'] : '';
        $tel = ! empty( $instance['tel'] ) ? $instance['tel'] : 'Telephone number';
        $email = ! empty( $instance['email'] ) ? $instance['email'] : 'Email address';
    ?>
        <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
            <input class="widefat" type ="text" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id( 'company' ); ?>">Company:</label>
            <input class="widefat" type ="text" id="<?php echo $this->get_field_id( 'company' ); ?>" name="<?php echo $this->get_field_name( 'company' ); ?>" value="<?php echo esc_attr( $company ); ?>" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id( 'tel' ); ?>">Your telephone number:</label>
            <input class="widefat" rows="10" type="text" id="<?php echo $this->get_field_id( 'tel' ); ?>" name="<?php echo $this->get_field_name( 'tel' ); ?>" value="<?php echo esc_attr( $tel ); ?>" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id( 'email' ); ?>">Your email address:</label>
            <input class="widefat" rows="10" type="text" id="<?php echo $this->get_field_id( 'email' ); ?>" name="<?php echo $this->get_field_name( 'email' ); ?>" value="<?php echo esc_attr( $email ); ?>" />
        </p>
    <?php }

    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;
        $instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
        $instance[ 'company' ] = strip_tags( $new_instance[ 'company' ] );
        $instance[ 'tel' ] = strip_tags( $new_instance[ 'tel' ] );
        $instance[ 'email' ] = strip_tags( $new_instance[ 'email' ] );
        return $instance;
    }

    public $args = array(
        'before_title'  => '<h4 class="widgettitle">',
        'after_title'   => '</h4>',
        'before_widget' => '<div class="widget-wrap">',
        'after_widget'  => '</div></div>'
    );

    function widget( $args, $instance ) {
        echo $args['before_widget'];
        $company = apply_filters( 'widget_company', $instance['company'] );
        $tel = $instance['tel'];
        $email = $instance['email'];
        wp_enqueue_style( 'wamp-widget' );
        if ( ! empty( $instance['title'] ) ) {
            echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
        } 
    ?>
        <div class="cta">
            <?php if ( ! empty( $company ) ) { echo  '<p>'.$company.'</p>' ; }; ?>
            <?php echo 'Call us on ' . $tel . ' or email <a href="' . $email . '">' . $email . '</a>'; ?>
        </div>
    <?php
        echo $args['after_widget'];
      }  
  
      function widget_enqueue_styles() {
          wp_register_style( 'wamp-widget', plugins_url( 'css/widget.css', __FILE__ ) );
      }
  
      function enqueue_admin_scripts() {
          wp_enqueue_script( 'my-widget-admin-script', plugins_url( 'admin-script.js', __FILE__ ) );
          wp_enqueue_style( 'my-widget-admin-style', plugins_url( 'admin-style.css', __FILE__ ) );
      }
  
      function widget_display_callback( $instance, $widget, $args ) {
          // 위젯 출력 전에 추가 작업 수행
          return $instance;
      }
  
      function widget_update_callback( $instance, $new_instance, $old_instance ) {
          // 위젯 업데이트 전에 추가 작업 수행
          return $instance;
      }
  
  }
  
  $my_widget = new Wamp_Widget();
  

 

설명

__construct 메서드

  • 기능: 위젯의 기본 속성을 설정하고, 위젯을 초기화합니다. widgets_init 액션 훅을 통해 위젯을 등록하고, 프론트엔드와 백엔드 스크립트 및 스타일을 큐잉합니다.

form 메서드

  • 기능: 위젯 설정 폼을 생성합니다. 관리자가 위젯 설정 페이지에서 값을 입력할 수 있도록 폼 필드를 제공합니다.
  • 코드 설명:
    • title, company, tel, email 등의 설정 값을 가져오고 기본값을 설정합니다.
    • 폼 필드를 생성하여 관리자가 값을 입력할 수 있도록 합니다.

update 메서드

  • 기능: 새로운 설정 값을 저장하고 기존 값을 업데이트합니다.
  • 코드 설명:
    • 새로운 값 ($new_instance)을 받아서 기존 값 ($old_instance)을 업데이트합니다.
    • strip_tags를 사용하여 입력 값에서 HTML 태그를 제거합니다.

widget 메서드

  • 기능: 위젯의 HTML 출력을 생성합니다.
  • 코드 설명:
    • 설정 값 ($instance)을 가져와서 HTML 출력에 사용합니다.
    • wp_enqueue_style을 사용하여 프론트엔드 스타일을 큐잉합니다.
    • 위젯 제목과 내용(회사명, 전화번호, 이메일 주소)을 출력합니다.

widget_enqueue_styles 메서드

  • 기능: 프론트엔드에서 사용할 CSS 파일을 등록합니다.
  • 코드 설명:
    • wp_register_style을 사용하여 위젯 스타일을 등록합니다.

enqueue_admin_scripts 메서드

  • 기능: 백엔드(관리자 페이지)에서 사용할 JavaScript 및 CSS 파일을 큐잉합니다.
  • 코드 설명:
    • wp_enqueue_script와 wp_enqueue_style을 사용하여 관리자 페이지에서 사용할 스크립트와 스타일을 큐잉합니다.

widget_display_callback 메서드

  • 기능: 위젯이 출력되기 전에 추가 작업을 수행할 수 있습니다.
  • 코드 설명:
    • 출력 전에 인스턴스 값을 수정하거나 추가 작업을 수행할 수 있습니다.

widget_update_callback 메서드

  • 기능: 위젯이 업데이트되기 전에 추가 작업을 수행할 수 있습니다.
  • 코드 설명:
    • 업데이트 전에 인스턴스 값을 수정하거나 추가 작업을 수행할 수 있습니다.

이러한 메서드들은 워드프레스 위젯의 기본적인 기능을 확장하고, 사용자 지정 기능을 추가하는 데 유용합니다.