Wordpress:自定义循环以排除在小部件 $args 中分配的帖子 ID [英] Wordpress: Custom loop to exclude post id assigned within widget $args
问题描述
在 function.php
中注册小部件以显示定义的 post_id 元:
Having widget registered in function.php
to display defined post_id meta:
class featured_widget extends WP_Widget
{
/**
* Display front-end contents.
*/
function widget($args, $instance)
{
$post = get_post($instance['post_id']);
...
}
}
我想从循环中排除分配的 $post
的 post_id
:
I want to exclude the assigned post_id
of $post
from my loop:
if (have_posts()) : while (have_posts()) : the_post();
推荐答案
1.如何获取post_id
值?
WordPress 将小部件数据存储在选项表中,option_name
是 widget_{$id_base}
.例如,当您构建这样的小部件时:
1. How to get the post_id
value?
WordPress stores widget data in the options table with option_name
is widget_{$id_base}
. Example, when you construct a widget like this:
function __construct() {
parent::__construct('so37244516-widget',
__('A label', 'text-domain'), [
'classname' => 'so37244516-widget-class',
'description' => __('Some descriptions', 'text-domain')
]);
}
option_name
应该是 widget_so37244516-widget
.然后要检索小部件数据,我们只需要使用:
The option_name
should be widget_so37244516-widget
. Then to retrieve the widget data, we just need to use:
$data = get_option('widget_so37244516-widget');
但是,因为一个小部件可以有多个实例,$data
是一个具有不可预测键的关联数组.(每次我们将小部件拖入侧边栏并保存时,都会返回小部件的一个新实例).
But, because a widget can have multiple instances, $data
is an associative array with unpredictable keys. (Each time we drag a widget into a sidebar and save it, a new instance of the widget is returned).
因此,如果整个站点中只有一个小部件实例,$data[2]['post_id']
就是我们需要的值.如果有多个实例,我们需要遍历$data
,比较一些键和值以找出正确的.一如既往,var_dump($data)
非常有帮助.
So if there's only one instance of the widget throughout your site, $data[2]['post_id']
is the value we need. And if there're multiple instances, we need to loop through $data
, compare some keys and values to find out the correct one. As always, var_dump($data)
is very helpful.
假设 $exclude_id
是我们从第 1 步得到的值.
Suppose $exclude_id
is the value we got from step 1.
- 您正在执行自定义循环,请使用@hemnath_mouli 的方法:
$query = new WP_Query([
'post__not_in' => [$exclude_id]
]);
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
// Do loop.
endwhile;
wp_reset_query(); // Must have.
else :
// Do something.
endif;
记得做wp_reset_query()
.
- 您正在使用默认循环,请在您的
functions.php
中尝试@Deepti_chipdey 的方法:
- You're using default loop, try @Deepti_chipdey's method in your
functions.php
:
add_action('pre_get_posts', function($query)
{
if ( $query->is_home() && $query->is_main_query() ) {
$query->set('post__not_in', [$exclude_id]);
}
});
确保将 is_home()
更改为您的偏好页面.
Make sure to change is_home()
to your preference page.
这篇关于Wordpress:自定义循环以排除在小部件 $args 中分配的帖子 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!