根据OP中给出的代码,很难准确地告诉您哪里出了问题。请注意我所能做的,你永远不要使用create_function()
, 这是一个可被黑客利用的安全线程。你应该避免完全使用它。而是利用适当的closures 这是在PHP 5.3中引入的。
为了帮助您,这里有一个基本框架,您可以使用它来构建小部件。请注意,由于使用了new short array syntax ([]
)
class Custom_Services extends WP_Widget
{
public function __construct()
{
parent::__construct(
\'widget_custom_service\',
_x( \'Custom Service Widget\', \'Custom Service Widget\' ),
[ \'description\' => __( \'Displays information from a custom service.\' ) ]
);
$this->alt_option_name = \'widget_custom_service\';
add_action( \'save_post\', [$this, \'flush_widget_cache\'] );
add_action( \'deleted_post\', [$this, \'flush_widget_cache\'] );
add_action( \'switch_theme\', [$this, \'flush_widget_cache\'] );
}
public function widget( $args, $instance )
{
$cache = [];
if ( ! $this->is_preview() ) {
$cache = wp_cache_get( \'widget_services\', \'widget\' );
}
if ( ! is_array( $cache ) ) {
$cache = [];
}
if ( ! isset( $args[\'widget_id\'] ) ) {
$args[\'widget_id\'] = $this->id;
}
if ( isset( $cache[ $args[\'widget_id\'] ] ) ) {
echo $cache[ $args[\'widget_id\'] ];
return;
}
ob_start();
$title = ( ! empty( $instance[\'title\'] ) ) ? $instance[\'title\'] : __( \'Category Posts\' );
/** This filter is documented in wp-includes/default-widgets.php */
$title = apply_filters( \'widget_title\', $title, $instance, $this->id_base );
// ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END
echo $args[\'after_widget\'];
if ( ! $this->is_preview() ) {
$cache[ $args[\'widget_id\'] ] = ob_get_flush();
wp_cache_set( \'widget_services\', $cache, \'widget\' );
} else {
ob_end_flush();
}
}
public function update( $new_instance, $old_instance )
{
$instance = $old_instance;
$instance[\'title\'] = strip_tags( $new_instance[\'title\'] );
$this->flush_widget_cache();
$alloptions = wp_cache_get( \'alloptions\', \'options\' );
if ( isset($alloptions[\'widget_custom_service\']) )
delete_option(\'widget_custom_service\');
return $instance;
}
public function flush_widget_cache()
{
wp_cache_delete(\'widget_services\', \'widget\');
}
public function form( $instance )
{
$title = isset( $instance[\'title\'] ) ? esc_attr( $instance[\'title\'] ) : \'\';
?>
<p>
<label for="<?php echo $this->get_field_id( \'title\' ); ?>"><?php _e( \'Title:\' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( \'title\' ); ?>" name="<?php echo $this->get_field_name( \'title\' ); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<?php
}
}
add_action( \'widgets_init\', function ()
{
register_widget( \'Custom_Services\' );
});