如何在其它地方调用小工具的设置值

WordPress1 181阅读模式

有些情况下,需要在其它地方调用某个小工具的设置值 ,比如文章数量,该如何实现,下面是个简单的例子仅供开发者参考。

比如,注册的小工具名称为:latest_article_widget,该小工具设置文章数量的字段名称为:number。

// 获取该小工具设置组数
$widget_instances = get_option( 'widget_latest_article_widget' );
$number_value = '';
if ( is_array( $widget_instances ) ) {
	foreach ( $widget_instances as $key => $value ) {
		if ( isset( $value['number'] ) ) {
			$number_value = $value['number'];
			break;
		}
	}
}

// 输出
echo $number_value;

上面的代码适合该小工具只添加出现一次的情况,当添加多个时会读取编号小的数据。

想调用指定添加的小工具数据,可以用下面的代码:

$widget_instances = get_option( 'widget_latest_article_widget' );

if ( is_array( $widget_instances ) && isset( $widget_instances[6]['number'] ) ) {
	$number_value = $widget_instances[6]['number'];
} else {
	$number_value = '';
}

echo $number_value;

其中数字6,是该小工具的编号,可以通过查看小工具的源代码获得。

或者将下面代码添加到当前主题的 functions.php 文件中

function get_widget_ids_in_sidebar($sidebar_id) {
	$widget_ids = array();
	// 获取指定侧边栏中的小工具列表
	$sidebars_widgets = wp_get_sidebars_widgets();
	if (isset($sidebars_widgets[$sidebar_id])) {
		$widget_ids = $sidebars_widgets[$sidebar_id];
	}
    return $widget_ids;
}

// 在侧边栏中输出小工具编号
$sidebar_id = 'sidebar-1'; // 侧边栏的ID
$widget_ids = get_widget_ids_in_sidebar($sidebar_id);

// 遍历小工具列表并输出小工具编号
foreach ($widget_ids as $widget_id) {
	echo "小工具编号:$widget_id<br>";
}

可以在侧边栏小工具中输出指定侧边栏添加的小工具名称和编号。

如何在其它地方调用小工具的设置值

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
    • 爱比宝
      爱比宝 0

      很实用的小技巧,学习了

    匿名

    发表评论

    匿名网友
    :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

    拖动滑块以完成验证