Skip to content

Instantly share code, notes, and snippets.

@erkarp
Last active January 30, 2018 15:34
Show Gist options
  • Save erkarp/1ce889981bbb3be33f31eae6abbcf55c to your computer and use it in GitHub Desktop.
Save erkarp/1ce889981bbb3be33f31eae6abbcf55c to your computer and use it in GitHub Desktop.
Basic WordPress widget to create a row with three resizable columns. Works best with Wing.
/**
* Class WPDocs_New_Widget
* https://github.com/KingPixil/wing/tree/master/src
*/
class Three_Columns extends WP_Widget {
function __construct() {
// Instantiate the parent object.
parent::__construct( false, __( 'Three Columns', 'textdomain' ), array(
'description' => __( 'Row with three resizable columns', 'textdomain' )
) );
}
function widget( $args, $instance ) {
echo $args['before_widget'];
$columns = '';
for ($x = 1; $x <= 3; $x++) {
$columns .= '<div class="' . $instance['width-'.$x] . '">' . $instance['text-'.$x] . '</div>';
}
echo '<div class="row">' . $columns . '</div>';
echo $args['after_widget'];
}
function update( $new_instance, $old_instance ) {
return $new_instance;
}
function form( $instance ) { ?>
<p><strong>The column widths should add up to 12.</strong></p>
<p>To use only two columns, add the first two columns to 12 and leave the third Text area empty.</p>
<?php for ($x = 1; $x <= 3; $x++) {
$width_var = 'width-' . $x;
$text_var = 'text-' . $x;
$col_width = ! empty( $instance[$width_var] ) ? $instance[$width_var] : __( 'col-4', 'text_domain' );
$col_text = ! empty( $instance[$text_var] ) ? $instance[$text_var] : __( '', 'text_domain' );
?>
<h3>Column <?php echo $x ?></h3>
<label for="<?php echo $this->get_field_id( 'col-' . $x . '-width' ); ?>">
<?php _e( 'Width' ); ?>
</label>
<select class="widefat"
id="<?php echo $this->get_field_id( 'width-' . $x ); ?>"
name="<?php echo $this->get_field_name( 'width-' . $x ); ?>"
value=" <?php echo esc_attr( $col_width ); ?>">
<?php for ($w = 1; $w <= 12; $w++) { ?>
<?php $className = 'col-' . $w ?>
<option
<?php if ($col_width == $className) echo 'selected' ?>
<?php echo 'value="' .$className . '" ' ?> >
<?php echo esc_attr( $className ); ?>
</option>
<?php } ?>
</select>
<label for="<?php echo $this->get_field_id( 'column-' . $x . '-text' ); ?>">
<?php _e( 'Text' ); ?>
</label>
<textarea class="widefat" rows="5" id="<?php echo $this->get_field_id( 'text-' . $x ); ?>"
name="<?php echo $this->get_field_name( 'text-' . $x ); ?>"><?php echo esc_attr( $col_text ); ?></textarea>
<?php } return '';
}
}
add_action( 'widgets_init', 'wpdocs_register_widgets' );
function wpdocs_register_widgets() {
register_widget( 'Three_Columns' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment