我有一个小部件,可以在侧边栏中显示相关帖子。 我想使用页面中的短代码来操作小部件的wp_query参数。
我想这样做的原因是它是一个多页帖子(带分页符),每个页面都与不同的类别相关。 我希望小部件根据特定页面显示推荐的帖子。
我不确定在运行wp_query之前如何让小部件评估短代码($a["cat"])
。
短代码功能:
//[bartag cat="computers"]
function bartag_func( $atts ) {
$a = shortcode_atts( array('cat' => ''), $atts );
return $a['cat'];
}
add_shortcode( 'bartag', 'bartag_func' );
小部件功能:
class related_articles_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
parent::__construct(
'related_articles_Widget', // Base ID
esc_html__( 'related_articles_Widget', 'text_domain' ), // Name
array( 'description' => esc_html__( '', 'text_domain' ), ) // Args
);
}
public function widget( $args, $instance ) {
echo $args['before_widget'];
$args = array( 'post_type' => 'post',
'posts_per_page' => 3,
'category_name' => $a['cat']
)
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
get_template_part( 'template-parts/content', 'small-article-template');
endwhile;
wp_reset_query();
}
}
function register_related_articles_Widget() {
register_widget( 'related_articles_Widget' );
}
add_action( 'widgets_init', 'register_related_articles_Widget' );
答案 0 :(得分:0)
在您的班级中声明短代码。我前几天刚刚做了这个,并使用本教程来帮助:https://code.tutsplus.com/articles/create-wordpress-plugins-with-oop-techniques--net-20153
编辑: 我会添加一个名为get_widget_contents($ cat);
的单独函数for (let item of this.data.items) {
for (let outfitArr of item.outfit) {
if (itemId == outfitArr.itemId) {
this.outfitData = outfitArr;
}
}
}
然后在你的短代码功能中执行以下操作:
function get_widget_contents($cat) {
$args = array( 'post_type' => 'post',
'posts_per_page' => 3,
'category_name' => $cat
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
get_template_part( 'template-parts/content', 'small-article-template');
endwhile;
wp_reset_query();
}
您的小部件功能也会调用单独的函数:
function bartag_func( $atts ) {
$a = shortcode_atts( array('cat' => ''), $atts );
return get_widget_contents($a['cat']);
}
add_shortcode( 'bartag', 'bartag_func' );
我没有测试过这个,但这应该有效。不确定你的get_template_part做了什么。对于短代码,可能需要返回一串HTML,以便将其置于正确的位置。如果是这种情况,只需将整个事物包装在ob_start()和ob_get_clean()
中