无法在一个回显中编写自定义窗口小部件代码

时间:2014-12-11 作者:Muhammad Hassan

我正在创建一个WordPress自定义小部件,我创建了下面的小部件,当我将其添加到function.php.

<?php
/* ------------------------------------------------------------------------- *
 *  Most Commented Post Widget
/* ------------------------------------------------------------------------- */
class show_popular_commented extends WP_Widget {

function show_popular_commented() {
 $widget_ops = array(\'classname\' => \'show_popular_commented\', \'description\' => __(\'Show your popular commented posts.\'));
 $this->WP_Widget(\'show_popular_commented\', __(\'EXE_Widgets - Popular Commented Posts\'), $widget_ops);
 }

function widget($args, $instance){
 extract($args);
 $title = $instance[\'title\'];
 $postscount = $instance[\'posts\'];
//Show The Most Commented Posts
 global $postcount;
 $myposts = get_posts(array(\'orderby\' => \'comment_count\',\'numberposts\' =>$postscount));
 echo $before_widget . $before_title . $title . $after_title; //Widget Data
 echo \'
 <style type="text/css">
 .commented_post {display:block;margin:10px 0;border-bottom:1px solid #DEDEDE;}
 .commented_post h4{font-size:16px;clear:both;display:block;}
 .commented_post p{font-size:13px;text-align:justify;line-height:18px;margin:10px 0;}
 </style>
 \';
 foreach($myposts as $post){
 setup_postdata($post);
 echo \'<div class="commented_post">\';
 echo \'<h4><a href="\';
 echo the_permalink();
 echo \'">\';
 echo the_title();
 echo\'</a></h4>\';
 echo the_excerpt();
 echo \'</div>\';
 }
 echo $after_widget;  //Widget Data
//Show The Most Commented Posts
 }


function update($newInstance, $oldInstance){
 $instance = $oldInstance;
 $instance[\'title\'] = strip_tags($newInstance[\'title\']);
 $instance[\'posts\'] = $newInstance[\'posts\'];
 return $instance;
 }

function form($instance){
 if(empty($instance[\'title\'])){ $instance[\'title\'] = \'\';}{
 echo \'<p><label  for="\'.$this->get_field_id(\'title\').\'">\' . __(\'Title:\') . \' </label><input style="width:100%;" id="\'.$this->get_field_id(\'title\').\'"  name="\'.$this->get_field_name(\'title\').\'" type="text"  value="\'.$instance[\'title\'].\'" /></p>\';
 }
 if(empty($instance[\'posts\'])){ $instance[\'posts\'] = \'\';}{
 echo \'<p><label  for="\'.$this->get_field_id(\'posts\').\'">\' . __(\'Number of Posts:\',  \'widgets\') . \' </label><input style="width:50px;" id="\'.$this->get_field_id(\'posts\').\'"  name="\'.$this->get_field_name(\'posts\').\'" type="text"  value="\'.$instance[\'posts\'].\'" /></p>\';
 }
 echo \'<input type="hidden" id="custom_recent" name="custom_recent" value="1" />\';
 }

 }

add_action(\'widgets_init\', create_function(\'\', \'return register_widget("show_popular_commented");\'));
?>
现在的问题是我不想用太多echo\'\'; 正如我在上面的代码中使用的那样。。。

 echo \'<div class="commented_post">\';
 echo \'<h4><a href="\';
 echo the_permalink();
 echo \'">\';
 echo the_title();
 echo\'</a></h4>\';
 echo the_excerpt();
 echo \'</div>\';
但是当我使用一个echo\'\'; 然后像下面这样对上面的一个进行编码,那么我的小部件工作不正常。它获取的是所有变量数据,但不是我写的HTML标记echo\'\';...

 echo \'<div class="commented_post"><h4><a href="\'.the_permalink().\'">\'.the_title().\'</a></h4>\'.the_excerpt().\'</div>\';
你能回答我为什么不接受单身echo\'\';?

2 个回复
最合适的回答,由SO网友:Milo 整理而成

从技术上讲,您的第一个示例也不正确,但问题并不明显。您使用的模板标记本身echo 他们的内容。例如,您可以简单地编写:

the_permalink();
echo, 将输出永久链接。这是因为echo它的价值。要在echo或变量赋值中输出permalink,需要使用get_permalink:

echo get_permalink()
几乎所有WordPress模板标记都具有等效的get_ 版本或切换的参数echoreturn, 喜欢the_title:

the_title( \'\', \'\', false );
此处第三个参数切换echo (正确)或return (错误)。

SO网友:Pieter Goosen

这应该是@Milo回答的扩展

您的代码中有几个缺陷

您不应该使用extract(). 很难调试,并导致意外输出。的所有实例extract() 已从核心中删除

PHP 5.2已经过时,因此5.3也已经过时。create_function() 是5.3之前的版本。这是一个巨大的安全风险eval() 这应该不惜一切代价避免。正确的方法就是function()

宁可使用WP_Query 代替get_posts(). WP_Query 缓存结果,使其更快

类名称单词应以camelcase开头

正确使用打开和关闭php标记,避免过度使用echo

我已经重写了您的完整小部件,使其与当前Widget API. 您可以只进行要添加或删除的调整

/* ------------------------------------------------------------------------- *
 *  Most Commented Post Widget
/* ------------------------------------------------------------------------- */
class Show_Popular_Commented extends WP_Widget {

    public function __construct() {
        parent::__construct(
            \'show_popular_commented\', 
            __( \'Popular Commented Posts\' ), 
            array( \'description\' => __( \'Show your popular commented posts.\' ), 
            ) 
        );
        $this->alt_option_name = \'show_popular_commented\';

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

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

        if ( ! is_array( $cache ) ) {
            $cache = array();
        }

        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\'] : __( \'Commented Posts\' );
        /** This filter is documented in wp-includes/default-widgets.php */
        $title          = apply_filters( \'widget_title\', $title, $instance, $this->id_base );
        $number         = ( ! empty( $instance[\'number\'] ) ) ? absint( $instance[\'number\'] ) : 5;
        if ( ! $number ) {
            $number = 5;
        }

        /**
         * Filter the arguments for the Commented Posts widget.
         *
         * @since 1.0.0
         *
         * @see WP_Query::get_posts()
         *
         * @param array $args An array of arguments used to retrieve the commented posts.
         */
        $query_args = [
            \'posts_per_page\'    => $number,
            \'orderby\'           => \'comment_count\',
        ];
        $q = new WP_Query( apply_filters( \'comment_posts_args\', $query_args ) );

        if( $q->have_posts() ) {

            echo $args[\'before_widget\'];
            if ( $title ) {
                echo $args[\'before_title\'] . $title . $args[\'after_title\'];
            }               

            while( $q->have_posts() ) {
                $q->the_post(); ?>

                <div class="commented_post">
                    <style type="text/css">
                        .commented_post {display:block;margin:10px 0;border-bottom:1px solid #DEDEDE;}
                        .commented_post h4{font-size:16px;clear:both;display:block;}
                        .commented_post p{font-size:13px;text-align:justify;line-height:18px;margin:10px 0;}
                    </style>

                    <header class="entry-header">
                        <?php the_title( \'<h1 class="entry-title"><a href="\' . esc_url( get_permalink() ) . \'" rel="bookmark">\', \'</a></h1>\' ); ?>
                    </header><!-- .entry-header -->

                    <div class="entry-summary">
                        <?php the_excerpt(); ?>
                    </div><!-- .entry-summary -->

                </div><!-- #post-## -->

                <?php
            }


            wp_reset_postdata();
        }
            echo $args[\'after_widget\']; 

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

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

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

        return $instance;
    }

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

    public function form( $instance ) {

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

        <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>

        <p>
            <label for="<?php echo $this->get_field_id( \'number\' ); ?>"><?php _e( \'Number of posts to show:\' ); ?></label>
            <input id="<?php echo $this->get_field_id( \'number\' ); ?>" name="<?php echo $this->get_field_name( \'number\' ); ?>" type="text" value="<?php echo $number; ?>" size="3" />
        </p>

    <?php
    }

}

add_action( \'widgets_init\', function () {
    register_widget( \'Show_Popular_Commented\' );
});

结束

相关推荐

Page full of widgets?

有没有可能创建一个只有很多小部件的页面?我看到的大多数WP站点的小部件都在侧边栏中,但我想要一个只有小部件而没有其他内容的页面。我当前使用的主题允许我向页面添加列或表,但我不知道(在任何主题中)是否可以向这些列或表单元格添加小部件?