Php Wordpress为小部件区域添加过滤条件
我为在functions.php中定义的添加了自定义模板:Php Wordpress为小部件区域添加过滤条件,php,wordpress,Php,Wordpress,我为在functions.php中定义的添加了自定义模板: add_filter('sp_template_image-widget_widget.php','my_template_filter'); function my_template_filter($template) { return get_template_directory() . '/widget-templates/image-widget-custom.php'; } 此模板(image widget custom
add_filter('sp_template_image-widget_widget.php','my_template_filter');
function my_template_filter($template) {
return get_template_directory() . '/widget-templates/image-widget-custom.php';
}
此模板(image widget custom.php)的内容如下所示:
<?php
/**
* Widget template. This template can be overriden using the "sp_template_image-widget_widget.php" filter.
* See the readme.txt file for more info.
*/
// Block direct requests
if ( !defined('ABSPATH') )
die('-1');
echo '<div class="col-sm-3 footer-blocks">';
echo $before_widget;
$output = "";
$output .= '<a href="' . $instance[link] . '">';
$output .= '<div class="hover-wrapper">';
$output .= '<div class="hover-inner">';
$output .= '<div class="hover-border">';
$output .= '<h2 class="text-uppercase">' . $instance[title] . '</h2>';
$output .= '</div>';
$output .= '</div>';
$output .= '<img class="img-responsive" src="' . $instance[imageurl] . '" alt="Footer image">';
$output .= '</div>';
$output .= '</a>';
echo $output;
echo $after_widget;
echo '</div>';
?>
唯一的问题是,我希望小部件被格式化为一个特定的小部件区域,而不是在wordpress网站上的任何地方。我希望应用模板的区域位于页脚中:
<?php dynamic_sidebar( 'footer-blocks' ); ?>
这可能吗?是的,这是可能的
一种方法(假设您可以修改主题模板文件)是在侧栏调用之前添加过滤器,然后在侧栏调用之后删除过滤器
删除主题文件中的add_过滤器
,然后按如下方式修改代码:
<?php
// Add the filter just before the sidebar is called
add_filter('sp_template_image-widget_widget.php','my_template_filter');
// Call the sidebar, which will use your custom template
dynamic_sidebar( 'footer-blocks' );
// Remove the filter to ensure any other sidebars do not use custom template
remove_filter('sp_template_image-widget_widget.php','my_template_filter');
?>
非常感谢你,我使用了你的替代方法,这对我很有效。
add_action( 'dynamic_sidebar_before', 'my_sidebar_checker', 10, 2);
add_action( 'dynamic_sidebar_after', 'my_sidebar_checker_after', 10, 2);
function my_sidebar_checker( $index, $bool ) {
if ( 'footer-blocks' == $index ) {
// Add the filter just before the sidebar is called
add_filter('sp_template_image-widget_widget.php','my_template_filter');
}
}
function my_sidebar_checker_after( $index, $bool ) {
if ( 'footer-blocks' == $index ) {
// Remove the filter to ensure any other sidebars do not use custom template
remove_filter('sp_template_image-widget_widget.php','my_template_filter');
}
}