首页 > 解决方案 > 从模板文件以编程方式修改 wordpress 小部件?

问题描述

在我的 WordPress 网站中,我希望每个月档案页面都有一个菜单,其中列出了该月在侧边栏中发布的所有帖子。我希望菜单根据用户所在的月份页面自动更新。

我创建了一个自定义小部件,列出了特定月份和年份的所有页面。但我不知道如何更新小部件以显示每个月页面的月份和年份。我最好的想法是以某种方式将 template.php 文件中的月/年参数传递给小部件类,但我不知道该怎么做。

那么,有没有办法从模板文件中更改侧边栏中的小部件变量?

这是我在从 WP_Widget 扩展的小部件类中的小部件函数,位于 functions.php 中。它包含我想为每个存档页面更改的变量。

public function widget( $args, $instance ) {
    $title = apply_filters( 'widget_title', $instance['title'] );

    // before and after widget arguments are defined by themes
    echo $args['before_widget'];
    if ( ! empty( $title ) ) {
        echo $args['before_title'] . $title . $args['after_title'];
    }
    // Output of Widget
    $query = array(
        'numberposts' => -1,
        'monthnum' => 6, //I would like to change this dynamically
        'year' => 2020, //I would like to change this dynamically
        'orderby' => !empty($instance['orderby']) ? $instance['orderby'] : 'name',
        'order' => !empty($instance['order']) ? $instance['order'] : 'asc'
    );
    $posts = get_posts( $query );
    if (!empty($posts)) {
        echo '<ul>';
        foreach( $posts as $post) {
            echo '<li>';
            echo '<a href="#before-post-' . $post->ID . '">'
                . $post->post_title . '</a></li>';
        }
        echo '</ul>';
    } else {
        echo 'Sorry. No articles have been added to this month\'s newsletter yet.';
    }
    echo $args['after_widget'];
}

我将它添加到sidebar-month从前端调用的侧边栏,然后我从 archives.php 使用get_sidebar('month'). 这是我的 archives.php 文件:

<div class="wrapper u-t-margin">
    <div class="columns columns--gutters">

        <div id="primary" class="content-area columns__md-8 u-b-margin">
            <main id="main" class="site-main" role="main">

                <?php
                if ( have_posts() ) {
                    ?>

                    <header class="page-header gx-card-content gx-card-content--same-md-y u-b-margin">
                        <?php
                        the_archive_title( '<h1 class="page-title archive-title">', ' Newsletter</h1>' );
                        the_archive_description( '<div class="archive-description">', '</div>' );
                        ?>
                    </header>

                    <?php
                    while ( have_posts() ) {
                        the_post();
                    ?><div id="before-post-<?php the_ID() ?>"></div>
                    <?php
                        get_template_part( 'template-parts/content', get_post_type() );
                    }

                    the_posts_pagination();
                } else {
                    get_template_part( 'template-parts/content', 'none' );
                }
                ?>

            </main>
        </div>

        <?php get_sidebar(); ?>

    </div>
</div>

标签: phpwordpresswidgetcustom-wordpress-pages

解决方案


推荐阅读