我有包含文本的文本小部件。我想以编程方式编辑该文本。
有没有办法做到这一点?
我有包含文本的文本小部件。我想以编程方式编辑该文本。
有没有办法做到这一点?
我想您应该根据小部件的标题来定位它,因此可以尝试以下功能:
/**
* Update a widget text located by it\'s title
*
* @see https://wordpress.stackexchange.com/a/155518/26350
*
* @param string $search_title
* @param string $new_text
* @param boolean
*/
function wpse_155046_update_widget_text_by_title( $search_title, $new_text )
{
// Get all data from text widgets
$widgets = get_option( \'widget_text\' );
foreach( $widgets as $key => $widget )
{
// Compare and ignore case:
if( mb_strtolower( $search_title ) === mb_strtolower( $widget[\'title\'] ) )
{
// Replace the widget text:
$widgets[$key][\'text\'] = $new_text;
// Update database and exit on first found match:
return update_option( \'widget_text\', $widgets );
}
}
return false;
}
其中,我们只替换与给定标题匹配的第一个小部件实例的文本。if( wpse_155046_update_widget_text_by_title(
\'My fruits\',
\'Five green apples and nine oranges.\'
)
)
{
echo \'success\';
}
else
{
echo \'no success\';
}
我们将小部件的文本替换为标题“我的水果”。Before:
After:
您也可以退房my answer here 控件数据在数据库中的位置。
/**
* Update a widget text located by it\'s instance number
*
* @see https://wordpress.stackexchange.com/a/155518/26350
*
* @param string $id
* @param string $new_text
* @param boolean
*/
function wpse_155046_update_widget_text_by_instance_number( $instance_number, $new_text )
{
// Get all data from text widgets
$widgets = get_option( \'widget_text\' );
if( isset( $widgets[$instance_number][\'text\'] ) )
{
// Replace the widget text:
$widgets[$instance_number][\'text\'] = $new_text;
// Update database and exit on first found match:
return update_option( \'widget_text\', $widgets );
}
return false;
}
我已经创建了一个wordpress小部件。它在小部件选项中有一个下拉列表。下拉列表包含“facebook”和“twitter”。如果管理员选择“twitter”,那么twitter关注者计数将显示在小部件中,与facebook的情况类似。使用jquery,该计数显示在id为“social count”的div中。当页面加载时,jquery ajax将获取计数并将其插入到“社交计数”中。问题是它在单个实例中运行良好。但是,如果在侧栏中添加了2个实例,则在这两个实例中都会显示最新的计数,因为我使用的是$(“.