是否可以使用任何过滤器或挂钩?
#1 楼
要扩展Mark的答案,默认WordPress小部件(也许widget_text
除外)中的过滤器方式通常不多(通常)。但是添加自己的自定义小部件很容易-将其放入您的
functions.php
:require_once("my_widget.php");
add_action("widgets_init", "my_custom_widgets_init");
function my_custom_widgets_init(){
register_widget("My_Custom_Widget_Class");
}
然后,您只需要将主题中的现有类别小部件从
wp-includes/widgets/class-wp-widget-categories.php
复制到my_widget.php
,然后将类名称更改为与使用的名称相同的名称在上面对register_widget()
的调用中。然后进行所需的任何更改!我建议也更改标题,以便您可以将其与默认的Categories小部件区分开。
#2 楼
您可以通过扩展默认WordPress小部件来覆盖它们。可以在以下链接上找到默认类别小部件的代码:https://developer.wordpress.org/reference/classes/wp_widget_categories/widget/,下面是如何使用示例代码覆盖小部件的输出。
Class My_Categories_Widget extends WP_Widget_Categories {
function widget( $args, $instance ) {
// your code here for overriding the output of the widget
}
}
function my_categories_widget_register() {
unregister_widget( 'WP_Widget_Categories' );
register_widget( 'My_Categories_Widget' );
}
add_action( 'widgets_init', 'my_categories_widget_register' );
评论
我之所以没有提供这种选择的原因是,您可能会在某个时候想要原始的行为,而使用您的解决方案,您只会失去获得它的能力。
–马克·卡普伦
16年6月15日在9:26
是的,如果您希望保留默认的小部件,最好注册一个全新的小部件。 codex.wordpress.org/Function_Reference/register_widget
– Boris Kuzmanov
16年6月15日在9:37
#3 楼
您无需创建完整的新窗口小部件即可执行所需的操作。当我阅读您的问题时,您只是对更改类别在前端的显示方式感兴趣。有两个功能可在前端显示类别wp_list_categories()
在列表中显示类别wp_dropdown_categories()
在下拉列表中显示类别这一切都取决于在后端中选择了什么选项
现在,这两个函数中的每一个都有一个特定于小部件的过滤器(分别为
widget_categories_args
和widget_categories_dropdown_args
),您可以使用它们来更改应传递给这些功能。您可以使用它来更改列表/下拉列表的行为。但是,这可能不足以完成您想要的操作。或者,每个函数都有其自己的过滤器,以完全改变这些函数应如何显示其输出的方式。
它们分别是
wp_list_categories
wp_dropdown_cats
我们可以使用
widget_title
过滤器专门针对小部件,而不能针对这些功能的其他实例。总之,您可以尝试以下操作:(完全未测试)
add_filter( 'widget_title', function( $title, $instance, $id_base )
{
// Target the categories base
if( 'categories' === $id_base ) // Just make sure the base is correct, I'm not sure here
add_filter( 'wp_list_categories', 'wpse_229772_categories', 11, 2 );
//add_filter( 'wp_dropdown_cats', 'wpse_229772_categories', 11, 2 );
return $title;
}, 10, 3 );
function wpse_229772_categories( $output, $args )
{
// Only run the filter once
remove_filter( current_filter(), __FUNCTION__ );
// Get all the categories
$categories = get_categories( $args );
$output = '';
// Just an example of custom html
$output .= '<div class="some class">';
foreach ( $categories as $category ) {
// Just an example of custom html
$output .= '<div class="' . echo $category->term_id . '">';
// You can add any other info here, like a link to the category
$output .= $category->name;
// etc ect, you get the drift
$output .= '</div>';
}
$output .= '</div>';
return $output;
}, 11, 2 );
评论
编写自己的小部件,该小部件可以满足您的需求。首先复制类别小部件的代码并进行修改。谢谢,我通常按照此技巧进行小部件修改。在我看来,这是更简单的方法。