除了结果,我的小部件上的一切都在工作!我创建了一个名为“国家名称”的分类法,用于几种自定义帖子类型。我创建这个小部件是为了显示所选国家的导游(CPT)。
该小部件在后端正常工作,但在前端没有得到任何结果(即“未找到列表”)。我在屏幕上回显了$实例,它是正确的,因此我的参数或查询肯定是错误的。有人能说出原因吗?
代码如下:
function widget($args, $instance) {
extract( $args );
$title = apply_filters(\'widget_title\', $instance[\'title\']);
$thiscountry = $instance[\'thiscountry\'];
$before_widget = \'<!-- \'.$thiscountry.\' -->\';
echo $before_widget;
if ( $title ) {
echo $before_title . $title . $after_title;
}
$this->getTourGuides($thiscountry);
echo $after_widget;
}
function getTourGuides($thiscountry) { //html
global $post;
$args = array(
\'posts_per_page\' => -1,
\'post_type\' => array( \'tourguides\' ),
\'tax_query\' => array(
array(
\'taxonomy\' => \'countryname\',
\'field\' => \'name\', // also tried \'slug\'
\'terms\' => $thiscountry,
),
),
);
//echo $thiscountry;
$listings = new WP_Query( $args);
if($listings->found_posts > 0) {
echo \'<ul class="guides_widget">\';
while ($listings->have_posts()) {
/* Get custom post type fields */
$ecpt_website = get_post_meta( get_the_ID(), \'ecpt_website\', true );
$listings->the_post();
$listItem = \'<li>\';
$listItem .= \'<a href="\' . $ecpt_website . \'">\';
$listItem .= get_the_title() . \'</a>\';
$listItem .= \'</li>\';
echo $listItem;
} // end while
echo \'</ul>\';
wp_reset_postdata();
}else{
echo \'<p style="padding:25px;">No listing found</p>\';
}
}
实例代码:
// constructor
function __construct() {
parent::__construct(
\'btn_tour_guides_by_country\', // Base ID
\'BTN Tour Guides by Country\', // Name
array(\'description\' => __( \'Display List of Tour Guides by Country in a Sidebar\'))
);
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance[\'title\'] = strip_tags($new_instance[\'title\']);
$instance[\'thiscountry\'] = strip_tags($new_instance[\'thiscountry\']);
return $instance;
}
// widget form creation
function form($instance) {
if( $instance) {
$title = esc_attr($instance[\'title\']);
$thiscountry = esc_attr($instance[\'thiscountry\']);
} else {
$title = \'Tour Operators\';
$thiscountry = \'\';
}
?>
<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(\'thiscountry\'); ?>"><?php _e(\'Country:\'); ?></label>
<select id="<?php echo $this->get_field_id(\'thiscountry\'); ?>" name="<?php echo $this->get_field_name(\'thiscountry\'); ?>">
<?php
$taxonomy = \'countryname\';
$queried_term = get_term_by( \'slug\', get_query_var($taxonomy) );
$terms = get_terms($taxonomy);
//echo $term->slug;
if ( $terms !== 0 ) {
foreach ( $terms as $term ) {?>
<?php
echo \'<option \'.selected($instance[\'thiscountry\'], $term->name).\' value="\' . $term->name . \'" id="\' . $term->name . \'">\', $term->name, \'</option>\';
?>
<?php
}
}
?>
<?php ?>
</select>
</p>
<?php
}