我的自定义帖子有特色图片。我需要通过widget检索它。我正在使用get\\u the\\u post\\u缩略图。但它不起作用。除此之外,小部件的其余部分工作正常。
下面是我的代码的简短摘录
<?php
class Employee extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
// Instantiate the parent object
$widget_ops = array(
\'classname\' => \'team_widget\',
\'description\' => \'Enter Empolyees to show them on front page.\',
);
parent::__construct( false, \'Show Empolyees\', $widget_ops );
}
public function widget( $args, $instance ) {
echo $args[\'before_widget\'];
if ( ! empty( $instance[\'photo\'] )) {
echo $args[\'before_image\']
.$instance[\'photo\']
.$args[\'after_image\']
}
echo $args[\'after_widget\'];
}
public function form( $instance ) {
if ( post_type_exists( \'employee\' ) ) :
$args = array(
\'type\' => \'post\',
\'child_of\' => 0,
\'parent\' => \'\',
\'orderby\' => \'name\',
\'order\' => \'ASC\',
\'hide_empty\' => 1,
\'hierarchical\' => 1,
\'exclude\' => \'\',
\'include\' => \'\',
\'number\' => \'\',
\'taxonomy\' => \'department\',
\'pad_counts\' => false,
\'posts_per_page\' => -1,
\'post_type\' => \'employee\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'department\',
\'field\' => \'slug\',
\'terms\' => \'department\',
)
)
);
$posts = get_posts( $args );
if ( ! empty( $posts ) && ! is_wp_error( $posts ) ) :
?>
<p>
<input type="checkbox" name="<?php echo $this->get_field_name( \'photo\' ); ?>"
value="<?php echo esc_html(get_the_post_thumbnail( $post->ID, \'thumbnail\' ) ) ?>"
<?php checked( $instance[\'photo\'], get_the_post_thumbnail( $post->ID, \'thumbnail\' ) ); ?> >Show Photo
<br>
</p>
<?php
endif; // chk posts based on terms.
endif;//chk post type endif.
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance[\'photo\'] = ( ! empty( $new_instance[\'photo\'] ) ) ? strip_tags( $new_instance[\'photo\'] ) : \'\';
return $instance;
}
}
最合适的回答,由SO网友:Tom J Nowell 整理而成
您的呼叫get_the_post_thumbnail
做工作,问题是你如何处理结果:
<input type="checkbox" name="<?php echo $this->get_field_name( \'photo\' ); ?>"
value="<?php echo esc_html(get_the_post_thumbnail( $post->ID, \'thumbnail\' ) ) ?>"
<?php checked( $instance[\'photo\'], get_the_post_thumbnail( $post->ID, \'thumbnail\' ) ); ?> >
不能将图像HTML标记放在其他标记属性中,这是无效的HTML。您还使用了一个去掉HTML的转义函数
esc_html
.
这永远不会奏效,也没有什么意义:
<input type="checkbox" name="test" value="<img src="example.com/img.png">">
相反,请考虑生成有效标记的内容,例如:
<label><input type="checkbox" name="test"><img src="example.com/img.png"></label>
或
<input type="checkbox" id="testid" name="test">
<label for="testid"><img src="example.com/img.png"></label>
See here for how to create labels for checkboxes, 记住使用
esc_attr
为了逃避
value