首页 WP开发教程 WordPress添加小工具框架AI教程

WordPress添加小工具框架AI教程

作者 WP导师

首先去framework文件夹或者inc文件夹添加widget.php文件,然后初始化widget:

<?php 
/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function codeblog_widgets_init() {
	register_sidebar(
		array(
			'name'          => esc_html__( 'Sidebar', 'codeblog' ),
			'id'            => 'sidebar-1',
			'description'   => esc_html__( 'Add widgets here.', 'codeblog' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);

	register_sidebar(
		array(
			'name'          => esc_html__( 'Footer', 'codeblog' ),
			'id'            => 'footer',
			'description'   => esc_html__( 'Add widgets here in footer.', 'codeblog' ),
			'before_widget' => '<div id="%1$s" class="col-md-4 col-xs-12 %2$s">',
			'after_widget'  => '</div>',
			'before_title'  => '<h3 class="footer-section-title">',
			'after_title'   => '</h3>',
		)
	);
}
add_action( 'widgets_init', 'codeblog_widgets_init' );

然后,去functions.php文件引入widget.php文件:

require_once get_template_directory() . ‘/framework/widget.php’;

然后在framework文件夹或者inc文件夹下面创建一个widgets的文件夹,添加全部小工具类的文件:

比方说你要创建一个展示最近评论带标题的小工具,就新建一个class-latest-widget-with-title.php的文件, 然后粘贴上自定义小工具的代码 , 首先要注册小工具:

/**
 * Register the widget
 */
function register_latest_comments_widget() {
    register_widget('Latest_Comments_Widget');
}
add_action('widgets_init', 'register_latest_comments_widget');

然后添加小工具代码:

<?php class Latest_Comments_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'latest_comments_widget',
            __('Latest Comments', 'textdomain'),
            array(
                'description' => __('Display the latest comments with avatars and post links', 'textdomain')
            )
        );
    }

    /**
     * Widget form in admin
     */
    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('Last Responses', 'textdomain');
        $number = !empty($instance['number']) ? $instance['number'] : 3;
        $excerpt_length = !empty($instance['excerpt_length']) ? $instance['excerpt_length'] : 50;
        $show_avatars = isset($instance['show_avatars']) ? $instance['show_avatars'] : true;
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>">
                <?php _e('Title:', 'textdomain'); ?>
            </label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" 
                   value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('number')); ?>">
                <?php _e('Number of comments to show:', 'textdomain'); ?>
            </label>
            <input class="tiny-text" id="<?php echo esc_attr($this->get_field_id('number')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('number')); ?>" type="number" 
                   step="1" min="1" value="<?php echo esc_attr($number); ?>" size="3">
        </p>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('excerpt_length')); ?>">
                <?php _e('Comment excerpt length (characters):', 'textdomain'); ?>
            </label>
            <input class="small-text" id="<?php echo esc_attr($this->get_field_id('excerpt_length')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('excerpt_length')); ?>" type="number" 
                   step="1" min="10" value="<?php echo esc_attr($excerpt_length); ?>">
        </p>
        <p>
            <input class="checkbox" type="checkbox" <?php checked($show_avatars); ?> 
                   id="<?php echo esc_attr($this->get_field_id('show_avatars')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('show_avatars')); ?>">
            <label for="<?php echo esc_attr($this->get_field_id('show_avatars')); ?>">
                <?php _e('Show avatars', 'textdomain'); ?>
            </label>
        </p>
        <?php
    }

    /**
     * Update widget settings
     */
    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        $instance['number'] = (!empty($new_instance['number'])) ? absint($new_instance['number']) : 3;
        $instance['excerpt_length'] = (!empty($new_instance['excerpt_length'])) ? absint($new_instance['excerpt_length']) : 50;
        $instance['show_avatars'] = isset($new_instance['show_avatars']);

        return $instance;
    }

    /**
     * Display the widget on frontend
     */
    public function widget($args, $instance) {
        $title = apply_filters('widget_title', $instance['title']);
        $number = !empty($instance['number']) ? absint($instance['number']) : 3;
        $excerpt_length = !empty($instance['excerpt_length']) ? absint($instance['excerpt_length']) : 50;
        $show_avatars = isset($instance['show_avatars']) ? $instance['show_avatars'] : true;

        echo $args['before_widget'];

        // Get latest approved comments
        $comments = get_comments(array(
            'status' => 'approve',
            'number' => $number,
            'post_status' => 'publish',
            'meta_query' => array(
                array(
                    'key' => 'comment_type',
                    'value' => array('pingback', 'trackback'),
                    'compare' => 'NOT IN'
                )
            )
        ));

        if (!empty($comments)) {
            ?>
            <div class="footer-section">
                <?php if ($title): ?>
                    <h3 class="footer-section-title"><?php echo esc_html($title); ?></h3>
                <?php endif; ?>
                
                <ul class="footer-section-content">
                    <?php foreach ($comments as $comment): 
                        $post = get_post($comment->comment_post_ID);
                        if (!$post) continue;
                        
                        $comment_excerpt = $this->get_comment_excerpt($comment->comment_content, $excerpt_length);
                        $avatar_url = $this->get_comment_avatar_url($comment->comment_author_email, 60);
                    ?>
                        <li class="footer-section-content-response">
                            <?php if ($show_avatars): ?>
                                <img src="<?php echo esc_url($avatar_url); ?>" 
                                     alt="<?php echo esc_attr($comment->comment_author); ?> Avatar" 
                                     class="comment-avatar">
                            <?php endif; ?>
                            
                            <div class="footer-section-content-response-wrapper">
                                <h4>
                                    <span class="response-author"><?php echo esc_html($comment->comment_author); ?></span> 
                                    <?php _e('in', 'textdomain'); ?>
                                    <a href="<?php echo esc_url(get_permalink($comment->comment_post_ID)); ?>#comment-<?php echo $comment->comment_ID; ?>" 
                                       class="response-subject light-link" 
                                       title="<?php echo esc_attr($post->post_title); ?>">
                                        <?php echo esc_html($post->post_title); ?>
                                    </a>
                                </h4>
                                <p class="mt-2"><?php echo esc_html($comment_excerpt); ?></p>
                            </div>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php
        } else {
            ?>
            <div class="footer-section">
                <?php if ($title): ?>
                    <h3 class="footer-section-title"><?php echo esc_html($title); ?></h3>
                <?php endif; ?>
                <p><?php _e('No comments found.', 'textdomain'); ?></p>
            </div>
            <?php
        }

        echo $args['after_widget'];
    }

    /**
     * Get comment excerpt
     */
    private function get_comment_excerpt($content, $length = 50) {
        $content = strip_tags($content);
        if (strlen($content) > $length) {
            $content = substr($content, 0, $length);
            $content = substr($content, 0, strrpos($content, ' '));
            $content .= '...';
        }
        return $content;
    }

    /**
     * Get avatar URL with fallback
     */
    private function get_comment_avatar_url($email, $size = 60) {
        $avatar_url = get_avatar_url($email, array('size' => $size));
        
        // Fallback to a default avatar if needed
        if (!$avatar_url) {
            $avatar_url = get_template_directory_uri() . '/img/webp/default-avatar.webp';
        }
        
        return $avatar_url;
    }
}

小工具代码可以由claude.ai生成,最精准:Act as a pro WordPress developer, convert this static HTML latest comments widget into dynamic: (这里是你的HTML小工具代码) ,如果你不需要AI提供样式你可以说no need the style codes

然后在widgets.php文件里,引入这个小工具文件:

## Custom Widgets ------------------------------------------------------------locate_template('framework/widgets/class-latest-widget-with-title.php.php',true,true);

前端怎么使用? 你懂的

您可能还喜欢

发表评论