挑选页面的小工具

Published
2023-08-06
浏览次数 :  57

<?php
class Custom_Page_Selector_Widget extends WP_Widget {
    // Constructor function.
    public function __construct() {
        parent::__construct(
            'custom_page_selector_widget',
            __('Custom Page Selector Widget', 'custom-page-selector-widget'),
            array(
                'description' => __('A custom widget to select specific pages and display them on the frontend.', 'custom-page-selector-widget'),
            )
        );
    }

    // Display the widget on the frontend.
    public function widget($args, $instance) {
        // Get the selected page IDs from widget settings.
        $page_ids = !empty($instance['page_ids']) ? $instance['page_ids'] : array();

        // Output widget content.
        echo $args['before_widget'];

        // Loop through selected page IDs and display their titles and content.
        foreach ($page_ids as $page_id) {
            $page = get_post($page_id);
            if ($page) {
                echo $args['before_title'] . $page->post_title . $args['after_title'];
                echo '<div class="page-content">' . apply_filters('the_content', $page->post_content) . '</div>';
            }
        }

        echo $args['after_widget'];
    }

    // Display widget settings form on the backend.
    public function form($instance) {
        $page_ids = !empty($instance['page_ids']) ? $instance['page_ids'] : array();
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('page_ids'); ?>"><?php _e('Select Pages:', 'custom-page-selector-widget'); ?></label>
            <select class="widefat" id="<?php echo $this->get_field_id('page_ids'); ?>" name="<?php echo $this->get_field_name('page_ids'); ?>[]" multiple>
                <?php
                $pages = get_pages();
                foreach ($pages as $page) {
                    $selected = in_array($page->ID, $page_ids) ? 'selected' : '';
                    echo '<option value="' . $page->ID . '" ' . $selected . '>' . $page->post_title . '</option>';
                }
                ?>
            </select>
        </p>
        <?php
    }

    // Update widget settings.
    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['page_ids'] = !empty($new_instance['page_ids']) ? array_map('intval', $new_instance['page_ids']) : array();
        return $instance;
    }
}

  • 标签1
  • 标签1
  • 标签1
Top