Add featured image to sidebar

时间:2016-03-01 作者:Katie Thompson

我正在处理其他人创建的自定义主题,我正在尝试向博客页面侧边栏中的小部件上方添加一个特色图像。我已经使用以下代码向页面侧边栏添加了一个特色图像:

<?php echo get_the_post_thumbnail( $post->ID, \'large\'); ?>
我需要向博客使用的任何模板添加相同的代码,但我找不到!我试过索引。php没有运气,我也没有看到任何其他模板文件。

我错过了什么??

EDIT: 他们创建了一个名为Blog的页面,并在阅读设置中将其设置为静态页面。我不知道哪个模板显示了这些帖子。

1 个回复
SO网友:Pieter Goosen

与其修改侧边栏或模板本身,不如创建一个插件,其中包含一个小部件,可以满足您的需要。这边

您不需要硬编码,可以保持动态。这也允许您随意移动小部件

您可以保持模板干净、简单且易于维护

用正确的方法做。小部件、注册自定义帖子类型、分类法和短代码之类的东西should always 在插件中注册,而不是在主题中注册

不久前,我编写了一个非常基本的小部件模板,您可以查看它here. 我们可以以此为基础创建自定义小部件。我将对您可以修改输出的部分进行注释。您还可以根据需要更改小部件。

让我们看看插件(只需在插件文件夹中创建一个文件,添加此代码并激活插件)

NOTE: 所有代码都未经测试,可能存在错误。此外,您需要安装PHP 5.4+才能正常工作

<?php
/*
Plugin Name: Blog Page Featured Image
Plugin URI:  https://wordpress.stackexchange.com/q/219344/31545
Description: Displays the blog page\'s feaured image in the sidear
Version:     1.0.0
Author:      Pieter Goosen
Author URI:  https://wordpress.stackexchange.com/users/31545/pieter-goosen
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

class Blog_Page_Featured_Image extends WP_Widget 
{

    public function __construct() 
    {
        parent::__construct(
            \'widget_blog_page_featured_image\', 
            _x( \'Blog Page Featured Image\', \'Blog page featured image\' ), 
            [ \'description\' => __( \'Displays the featured image for the pge set as blog page.\' ) ] 
        );
        $this->alt_option_name = \'widget_blog_page_featured_image\';

        add_action( \'save_post\',    [$this, \'flush_widget_cache\'] );
        add_action( \'deleted_post\', [$this, \'flush_widget_cache\'] );
        add_action( \'switch_theme\', [$this, \'flush_widget_cache\'] );
    }

    public function widget( $args, $instance ) 
    {
        $cache = [];
        if ( ! $this->is_preview() ) {
            $cache = wp_cache_get( \'widget_bpfi\', \'widget\' );
        }

        if ( ! is_array( $cache ) ) {
            $cache = [];
        }

        if ( ! isset( $args[\'widget_id\'] ) ) {
            $args[\'widget_id\'] = $this->id;
        }

        if ( isset( $cache[ $args[\'widget_id\'] ] ) ) {
            echo $cache[ $args[\'widget_id\'] ];
            return;
        }

        ob_start();

        $title          = ( ! empty( $instance[\'title\'] ) ) ? $instance[\'title\'] : __( \'Blog Page Featured Image\' );
        /** This filter is documented in wp-includes/default-widgets.php */
        $title          = apply_filters( \'widget_title\', $title, $instance, $this->id_base );

        // ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END
        // First make sure this is the page set as blogpage
        if (    \'page\' === get_option(\'show_on_front\')
             && is_home()
        ) { // We are on the blogpage
            // Get the current page object
            $page_object = $GLOBALS[\'wp_the_query\']->get_queried_object();

            // Make sure that the current page IS the one set as blogpage
            if ( $page_object->ID === (int) get_option( \'page_for_posts\' ) ) {
                /**
                 * Now that we are sure we are on the posts page, lets get and display
                 * its featured image. We will also first make sure that we
                 * actually have one set
                 */
                if ( has_post_thumbnail( $page_object->ID ) )
                    echo get_the_post_thumbnail( $page_object->ID );
            }
        }

        echo $args[\'after_widget\']; 

        if ( ! $this->is_preview() ) {
            $cache[ $args[\'widget_id\'] ] = ob_get_flush();
            wp_cache_set( \'widget_bpfi\', $cache, \'widget\' );
        } else {
            ob_end_flush();
        }
    }

    public function update( $new_instance, $old_instance ) 
    {
        $instance                   = $old_instance;
        $instance[\'title\']          = strip_tags( $new_instance[\'title\'] );
        $this->flush_widget_cache();

        $alloptions = wp_cache_get( \'alloptions\', \'options\' );
        if ( isset($alloptions[\'widget_blog_page_featured_image\']) )
            delete_option(\'widget_blog_page_featured_image\');

        return $instance;
    }

    public function flush_widget_cache() 
    {
        wp_cache_delete(\'widget_bpfi\', \'widget\');
    }

    public function form( $instance ) 
    {

        $title      = isset( $instance[\'title\'] ) ? esc_attr( $instance[\'title\'] ) : \'\';
        ?>

        <p>
            <label for="<?php echo $this->get_field_id( \'title\' ); ?>"><?php _e( \'Title:\' ); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id( \'title\' ); ?>" name="<?php echo $this->get_field_name( \'title\' ); ?>" type="text" value="<?php echo $title; ?>" />
        </p>

    <?php
    }

}

add_action( \'widgets_init\', function () 
{
    register_widget( \'Blog_Page_Featured_Image\' );
});
我还喜欢做的是,当一个小部件完全脱离上下文时,总是完全删除它,以避免在没有显示其他小部件时侧栏呈现空白

我们可以尝试与我描述的相同的方法here. 你可以在插件的底部添加这个

add_filter( \'sidebars_widgets\', function ( $sidebars_widgets )
{
    // Return our filter when we are on admin screen
    if ( is_admin() )
        return $sidebars_widgets;

    // Make sure we are not on the blog page, if we are, bail
    if (    \'page\' === get_option(\'show_on_front\')
         && is_home()
         && $GLOBALS[\'wp_the_query\']->get_queried_object_id() === (int) get_option( \'page_for_posts\' ) 
    )
        return $sidebars_widgets;

    /**
     * Widget we need to target. This should be the name/id we used to register it
     *
     * EXAMPLE
     *   parent::__construct(
            \'widget_blog_page_featured_image\', 
            _x( \'Blog Page Featured Image\', \'Blog page featured image\' ), 
            [ \'description\' => __( \'Displays the featured image for the pge set as blog page.\' ) ] 
        );
     *
     */
    $custom_widget  = \'widget_blog_page_featured_image\';

    // See if our custom widget exists is any sidebar, if so, get the array index
    foreach ( $sidebars_widgets as $sidebars_key=>$sidebars_widget ) {
        // Skip the wp_inactive_widgets set, we do not need them
        if ( $sidebars_key == \'wp_inactive_widgets\' )
        continue;

        // Only continue our operation if $sidebars_widget are not an empty array
        if ( $sidebars_widget ) {
            foreach ( $sidebars_widget as $k=>$v ) {

                /**
                 * Look for our custom widget, if found, unset it from the $sidebars_widgets array
                 * @see stripos()
                 */
                if ( stripos( $v, $custom_widget ) !== false ) 
                    unset( $sidebars_widgets[$sidebars_key][$k] );
            } // endforeach $sidebars_widget
        } // endif $sidebars_widget
    } // endforeach $sidebars_widgets

    return $sidebars_widgets;
});
编辑上面的代码现在已经过测试,并按预期工作

相关推荐

Check if sidebar is rendered?

我想检查前端是否有呈现的边栏,如果有,则输出一些主体类,以便我可以以不同的方式设置页面样式。我尝试使用is\\u active\\u侧边栏,但如果侧边栏包含某个小部件(处于活动状态),则返回true-我想检查页面上是否存在它。我该怎么做?我的代码如下所示:在我的单曲里。php<?php get_sidebar(); ?> 在我的侧边栏中。phpif ( ! is_active_sidebar() ) { // Add something here perhaps?&#