I created this PHP code in WordPress to add image to the menu, but it is duplicating a div where there is an add button and I don't know why, I need it to be only one and not two results of the div, in case I only want the left div... I'll add an image about what I'm talking about so you can analyze my problem!
Structure is placed inside function wp_post_thumbnail_only_html
I left only the action that passes the button to facilitate.
<?php
if ( !defined( 'ABSPATH' ) ) {
exit;
}
class SNAP_Menu_Image{
public function __construct() {
add_action( 'admin_init', array( $this, 'admin_init' ), 99 );
}
public function admin_init() {
if ( !has_action( 'wp_nav_menu_item_custom_fields' ) ) {
}
add_action( 'wp_nav_menu_item_custom_fields', array( $this, 'menu_item_custom_fields' ), 10, 4 );
}
public function file_is_displayable_image( $result, $path ) {
if ( $result ) {
return true;
}
$fileExtension = pathinfo( $path, PATHINFO_EXTENSION );
return in_array( $fileExtension, $this->additionalDisplayableImageExtensions );
}
public function menu_image_init() {
add_post_type_support( 'nav_menu_item', array( 'thumbnail' ) );
$this->image_sizes = apply_filters( 'menu_image_default_sizes', $this->image_sizes );
if (is_array($this->image_sizes)) {
foreach ($this->image_sizes as $name => $params) {
add_image_size($name, $params[0], $params[1], ( array_key_exists(2, $params) ? $params[2] : false ) );
}
}
load_plugin_textdomain( 'menu-image', false, basename( dirname( __FILE__ ) ) . '/languages' );
}
public function menu_image_nav_menu_manage_columns( $columns ) {
return $columns + array( 'image' => __( 'Image', 'menu-image' ) );
}
public function menu_image_save_post_action( $post_id, $post ) {
$menu_image_settings = array(
'menu_item_image_size',
'menu_item_image_title_position'
);
foreach ( $menu_image_settings as $setting_name ) {
if ( isset( $_POST[ $setting_name ][ $post_id ] ) && !empty( $_POST[ $setting_name ][ $post_id ] ) ) {
if ( $post->{"_$setting_name"} != $_POST[ $setting_name ][ $post_id ] ) {
update_post_meta( $post_id, "_$setting_name", esc_sql( $_POST[ $setting_name ][ $post_id ] ) );
}
}
}
}
public function wp_update_nav_menu_item_action( $item_menu_id, $menu_item_db_id ) {
global $sitepress, $icl_menus_sync;
if ( class_exists( 'SitePress' ) && $sitepress instanceof SitePress && class_exists( 'ICLMenusSync' ) && $icl_menus_sync instanceof ICLMenusSync ) {
static $run_times = array();
$menu_image_settings = array(
'menu_item_image_size',
'menu_item_image_title_position',
'thumbnail_id',
'thumbnail_hover_id',
);
foreach ( $icl_menus_sync->menus as $menu_id => $menu_data ) {
if ( !isset( $_POST[ 'sync' ][ 'add' ][ $menu_id ] ) ) {
continue;
}
$cache_key = md5( serialize( array( $item_menu_id, 'tax_nav_menu' ) ) );
$cache_group = 'get_language_for_element';
wp_cache_delete( $cache_key, $cache_group );
$lang = $sitepress->get_language_for_element( $item_menu_id, 'tax_nav_menu' );
if ( !isset( $run_times[ $menu_id ][ $lang ] ) ) {
$run_times[ $menu_id ][ $lang ] = 0;
}
$post_item_ids = array();
foreach ( $_POST[ 'sync' ][ 'add' ][ $menu_id ] as $id => $lang_array ) {
if ( array_key_exists( $lang, $lang_array ) ) {
$post_item_ids[ ] = $id;
}
}
if ( !array_key_exists( $run_times[ $menu_id ][ $lang ], $post_item_ids ) ) {
continue;
}
$orig_item_id = $post_item_ids[ $run_times[ $menu_id ][ $lang ] ];
$orig_item_meta = get_metadata( 'post', $orig_item_id );
foreach ( $menu_image_settings as $meta ) {
if ( isset( $orig_item_meta[ "_$meta" ] ) && isset( $orig_item_meta[ "_$meta" ][ 0 ] ) ) {
update_post_meta( $menu_item_db_id, "_$meta", $orig_item_meta[ "_$meta" ][ 0 ] );
}
}
$run_times[ $menu_id ][ $lang ] ++;
break;
}
}
}
public function menu_image_edit_nav_menu_walker_filter() {
return 'Menu_Image_Walker_Nav_Menu_Edit';
}
public function menu_image_wp_setup_nav_menu_item( $item ) {
if ( !isset( $item->thumbnail_id ) ) {
$item->thumbnail_id = get_post_thumbnail_id( $item->ID );
}
if ( !isset( $item->thumbnail_hover_id ) ) {
$item->thumbnail_hover_id = get_post_meta( $item->ID, '_thumbnail_hover_id', true );
}
if ( !isset( $item->image_size ) ) {
$item->image_size = get_post_meta( $item->ID, '_menu_item_image_size', true );
}
if ( !isset( $item->title_position ) ) {
$item->title_position = get_post_meta( $item->ID, '_menu_item_image_title_position', true );
}
return $item;
}
public function menu_image_nav_menu_link_attributes_filter( $atts, $item, $args, $depth = null ) {
$this->setProcessed( $item->ID );
$position = $item->title_position ? $item->title_position : apply_filters( 'menu_image_default_title_position', 'after' );
$class = ! empty( $atts[ 'class' ] ) ? $atts[ 'class' ] : '';
$class .= " menu-image-title-{$position}";
if ( $item->thumbnail_hover_id ) {
$class .= ' menu-image-hovered';
} elseif ( $item->thumbnail_id ) {
$class .= ' menu-image-not-hovered';
}
if ( ! empty( $args->walker ) && class_exists( 'FlatsomeNavDropdown' ) && $args->walker instanceof FlatsomeNavDropdown && ! is_null( $depth ) && $depth === 0 ) {
$class .= ' nav-top-link';
}
$atts[ 'class' ] = trim( $class );
return $atts;
}
public function menu_image_nav_menu_item_title_filter( $title, $item, $depth = null, $args = null) {
if (is_numeric($item)) {
$item = wp_setup_nav_menu_item( get_post( $item ) );
}
$image_size = $item->image_size ? $item->image_size : apply_filters( 'menu_image_default_size', 'menu-36x36' );
$position = $item->title_position ? $item->title_position : apply_filters( 'menu_image_default_title_position', 'after' );
$class = "menu-image-title-{$position}";
$this->setUsedAttachments( $image_size, $item->thumbnail_id );
$image = '';
if ( $item->thumbnail_hover_id ) {
$this->setUsedAttachments( $image_size, $item->thumbnail_hover_id );
$hover_image_src = wp_get_attachment_image_src( $item->thumbnail_hover_id, $image_size );
$margin_size = $hover_image_src[ 1 ];
$image = "<span class='menu-image-hover-wrapper'>";
$image .= wp_get_attachment_image( $item->thumbnail_id, $image_size, false, "class=menu-image {$class}" );
$image .= wp_get_attachment_image(
$item->thumbnail_hover_id, $image_size, false, array(
'class' => "hovered-image {$class}",
'style' => "margin-left: -{$margin_size}px;",
)
);
$image .= '</span>';;
} elseif ( $item->thumbnail_id ) {
$image = wp_get_attachment_image( $item->thumbnail_id, $image_size, false, "class=menu-image {$class}" );
}
$none = ''; // Sugar.
switch ( $position ) {
case 'hide':
case 'before':
case 'above':
$item_args = array( $none, $title, $image );
break;
case 'after':
default:
$item_args = array( $image, $title, $none );
break;
}
$title = vsprintf( '%s<span class="menu-image-title">%s</span>%s', $item_args );
return $title;
}
public function menu_image_nav_menu_item_filter( $item_output, $item, $depth, $args ) {
if ( $this->isProcessed( $item->ID ) ) {
return $item_output;
}
$attributes = !empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) . '"' : '';
$attributes .= !empty( $item->target ) ? ' target="' . esc_attr( $item->target ) . '"' : '';
$attributes .= !empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) . '"' : '';
$attributes .= !empty( $item->url ) ? ' href="' . esc_attr( $item->url ) . '"' : '';
$attributes_array = shortcode_parse_atts($attributes);
$image_size = $item->image_size ? $item->image_size : apply_filters( 'menu_image_default_size', 'menu-36x36' );
$position = $item->title_position ? $item->title_position : apply_filters( 'menu_image_default_title_position', 'after' );
$class = "menu-image-title-{$position}";
$this->setUsedAttachments( $image_size, $item->thumbnail_id );
$image = '';
if ( $item->thumbnail_hover_id ) {
$this->setUsedAttachments( $image_size, $item->thumbnail_hover_id );
$hover_image_src = wp_get_attachment_image_src( $item->thumbnail_hover_id, $image_size );
$margin_size = $hover_image_src[ 1 ];
$image = "<span class='menu-image-hover-wrapper'>";
$image .= wp_get_attachment_image( $item->thumbnail_id, $image_size, false, "class=menu-image {$class}" );
$image .= wp_get_attachment_image(
$item->thumbnail_hover_id, $image_size, false, array(
'class' => "hovered-image {$class}",
'style' => "margin-left: -{$margin_size}px;",
)
);
$image .= '</span>';;
$class .= ' menu-image-hovered';
} elseif ( $item->thumbnail_id ) {
$image = wp_get_attachment_image( $item->thumbnail_id, $image_size, false, "class=menu-image {$class}" );
$class .= ' menu-image-not-hovered';
}
$attributes_array['class'] = $class;
$attributes_array = apply_filters( 'menu_image_link_attributes', $attributes_array, $item, $depth, $args );
$attributes = '';
foreach ( $attributes_array as $attr_name => $attr_value ) {
$attributes .= "{$attr_name}=\"$attr_value\" ";
}
$attributes = trim($attributes);
$item_output = "{$args->before}<a {$attributes}>";
$link = $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$none = '';
switch ( $position ) {
case 'hide':
case 'before':
case 'above':
$item_args = array( $none, $link, $image );
break;
case 'after':
default:
$item_args = array( $image, $link, $none );
break;
}
$item_output .= vsprintf( '%s<span class="menu-image-title">%s</span>%s', $item_args );
$item_output .= "</a>{$args->after}";
return $item_output;
}
public function menu_image_add_inline_style_action() {
wp_register_style( 'menu-image', SF()->plugin_url() . '/assets/css/menu-image.css', array(), '1.1', 'all' );
wp_enqueue_style( 'menu-image' );
}
public function menu_image_admin_head_nav_menus_action() {
wp_enqueue_script( 'menu-image-admin', SF()->plugin_url() . '/assets/js/menu-image.js', array( 'jquery' ) );
wp_localize_script(
'menu-image-admin', 'menuImage', array(
'l10n' => array(
'uploaderTitle' => __( 'Chose menu image', 'menu-image' ),
'uploaderButtonText' => __( 'Select', 'menu-image' ),
),
'settings' => array(
'nonce' => wp_create_nonce( 'update-menu-item' ),
),
)
);
wp_enqueue_media();
wp_enqueue_style( 'editor-buttons' );
}
public function menu_image_delete_menu_item_image_action() {
$menu_item_id = (int) $_REQUEST[ 'menu-item' ];
check_admin_referer( 'delete-menu_item_image_' . $menu_item_id );
if ( is_nav_menu_item( $menu_item_id ) && has_post_thumbnail( $menu_item_id ) ) {
delete_post_thumbnail( $menu_item_id );
delete_post_meta( $menu_item_id, '_thumbnail_hover_id' );
delete_post_meta( $menu_item_id, '_menu_item_image_size' );
delete_post_meta( $menu_item_id, '_menu_item_image_title_position' );
}
}
public function wp_post_thumbnail_only_html( $item_id ) {
$default_size = apply_filters( 'menu_image_default_size', 'menu-36x36' );
$markup = '<p class="description description-thin" ><label>%s<br /><a title="%s" href="#" class="set-post-thumbnail button%s" data-item-id="%s" style="height: auto;">%s</a>%s</label></p>';
$thumbnail_id = get_post_thumbnail_id( $item_id );
$content = sprintf(
$markup,
esc_html__( 'Menu image', 'menu-image' ),
$thumbnail_id ? esc_attr__( 'Change menu item image', 'menu-image' ) : esc_attr__( 'Set menu item image', 'menu-image' ),
'',
$item_id,
$thumbnail_id ? wp_get_attachment_image( $thumbnail_id, $default_size ) : esc_html__( 'Set image', 'menu-image' ),
$thumbnail_id ? '' . __( 'Remove', 'menu-image' ) . '' : ''
);
return $content;
}
public function wp_post_thumbnail_html( $item_id ) {
$default_size = apply_filters( 'menu_image_default_size', 'menu-36x36' );
$content = $this->wp_post_thumbnail_only_html( $item_id );
$image_size = get_post_meta( $item_id, '_menu_item_image_size', true );
if ( !$image_size ) {
$image_size = $default_size;
}
$title_position = get_post_meta( $item_id, '_menu_item_image_title_position', true );
if ( !$title_position ) {
$title_position = apply_filters( 'menu_image_default_title_position', 'after' );
}
$content = "<div class='menu-item-images' style='min-height:70px'>$content</div>";
return apply_filters( 'admin_menu_item_thumbnail_html', $content, $item_id );
}
public function wp_ajax_set_menu_item_thumbnail() {
$json = !empty( $_REQUEST[ 'json' ] );
$post_ID = intval( $_POST[ 'post_id' ] );
if ( !current_user_can( 'edit_post', $post_ID ) ) {
wp_die( - 1 );
}
$thumbnail_id = intval( $_POST[ 'thumbnail_id' ] );
$is_hovered = (bool) $_POST[ 'is_hover' ];
check_ajax_referer( "update-menu-item" );
if ( $thumbnail_id == '-1' ) {
if ( $is_hovered ) {
$success = delete_post_meta( $post_ID, '_thumbnail_hover_id' );
} else {
$success = delete_post_thumbnail( $post_ID );
}
} else {
if ( $is_hovered ) {
$success = update_post_meta( $post_ID, '_thumbnail_hover_id', $thumbnail_id );
} else {
$success = set_post_thumbnail( $post_ID, $thumbnail_id );
}
}
if ( $success ) {
$return = $this->wp_post_thumbnail_only_html( $post_ID );
$json ? wp_send_json_success( $return ) : wp_die( $return );
}
wp_die( 0 );
}
public function menu_item_custom_fields( $item_id, $item, $depth, $args ){
?>
<div class="field-image hide-if-no-js wp-media-buttons">
<?php echo $this->wp_post_thumbnail_html( $item_id ) ?>
</div>
<?php
}
public function jetpack_photon_override_image_downsize_filter( $prevent, $data ) {
return $this->isAttachmentUsed( $data[ 'attachment_id' ], $data[ 'size' ] );
}
public function setUsedAttachments( $size, $id ) {
$this->used_attachments[ $size ][ ] = $id;
}
public function isAttachmentUsed( $id, $size = null ) {
if ( ! is_null( $size ) ) {
return is_string( $size ) && isset( $this->used_attachments[ $size ] ) && in_array( $id, $this->used_attachments[ $size ] );
} else {
foreach ( $this->used_attachments as $used_attachment ) {
if ( in_array( $id, $used_attachment ) ) {
return true;
}
}
return false;
}
}
public function wp_get_attachment_image_attributes( $attr, $attachment, $size ) {
if ( $this->isAttachmentUsed( $attachment->ID, $size ) ) {
unset( $attr['sizes'], $attr['srcset'] );
}
return $attr;
}
protected function setProcessed( $id ) {
$this->processed[] = $id;
}
protected function isProcessed( $id ) {
return in_array( $id, $this->processed );
}
}
$menu_image = new SNAP_Menu_Image();
require_once(ABSPATH . 'wp-admin/includes/nav-menu.php');
class Menu_Image_Walker_Nav_Menu_Edit extends Walker_Nav_Menu_Edit {
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
global $_wp_nav_menu_max_depth;
$_wp_nav_menu_max_depth = $depth > $_wp_nav_menu_max_depth ? $depth : $_wp_nav_menu_max_depth;
ob_start();
$item_id = esc_attr( $item->ID );
$removed_args = array(
'action',
'customlink-tab',
'edit-menu-item',
'menu-item',
'page-tab',
'_wpnonce',
);
$original_title = false;
if ( 'taxonomy' == $item->type ) {
$original_title = get_term_field( 'name', $item->object_id, $item->object, 'raw' );
if ( is_wp_error( $original_title ) )
$original_title = false;
} elseif ( 'post_type' == $item->type ) {
$original_object = get_post( $item->object_id );
$original_title = get_the_title( $original_object->ID );
} elseif ( 'post_type_archive' == $item->type ) {
$original_object = get_post_type_object( $item->object );
if ( $original_object ) {
$original_title = $original_object->labels->archives;
}
}
$classes = array(
'menu-item menu-item-depth-' . $depth,
'menu-item-' . esc_attr( $item->object ),
'menu-item-edit-' . ( ( isset( $_GET['edit-menu-item'] ) && $item_id == $_GET['edit-menu-item'] ) ? 'active' : 'inactive'),
);
$title = $item->title;
if ( ! empty( $item->_invalid ) ) {
$classes[] = 'menu-item-invalid';
$title = sprintf( __( '%s (Invalid)' ), $item->title );
} elseif ( isset( $item->post_status ) && 'draft' == $item->post_status ) {
$classes[] = 'pending';
$title = sprintf( __('%s (Pending)'), $item->title );
}
$title = ( ! isset( $item->label ) || '' == $item->label ) ? $title : $item->label;
$submenu_text = '';
if ( 0 == $depth )
$submenu_text = 'style="display: none;"';
?>
<li id="menu-item-<?php echo $item_id; ?>" class="<?php echo implode(' ', $classes ); ?>">
<div class="menu-item-bar">
<div class="menu-item-handle">
<span class="item-title"><span class="menu-item-title"><?php echo esc_html( $title ); ?></span> <span class="is-submenu" <?php echo $submenu_text; ?>><?php _e( 'sub item' ); ?></span></span>
<span class="item-controls">
<span class="item-type"><?php echo esc_html( $item->type_label ); ?></span>
<span class="item-order hide-if-js">
<a href="<?php
echo wp_nonce_url(
add_query_arg(
array(
'action' => 'move-up-menu-item',
'menu-item' => $item_id,
),
remove_query_arg($removed_args, admin_url( 'nav-menus.php' ) )
),
'move-menu_item'
);
?>" class="item-move-up" aria-label="<?php esc_attr_e( 'Move up' ) ?>">β</a>
|
<a href="<?php
echo wp_nonce_url(
add_query_arg(
array(
'action' => 'move-down-menu-item',
'menu-item' => $item_id,
),
remove_query_arg($removed_args, admin_url( 'nav-menus.php' ) )
),
'move-menu_item'
);
?>" class="item-move-down" aria-label="<?php esc_attr_e( 'Move down' ) ?>">β</a>
</span>
<a class="item-edit" id="edit-<?php echo $item_id; ?>" href="<?php
echo ( isset( $_GET['edit-menu-item'] ) && $item_id == $_GET['edit-menu-item'] ) ? admin_url( 'nav-menus.php' ) : add_query_arg( 'edit-menu-item', $item_id, remove_query_arg( $removed_args, admin_url( 'nav-menus.php#menu-item-settings-' . $item_id ) ) );
?>" aria-label="<?php esc_attr_e( 'Edit menu item' ); ?>"><span class="screen-reader-text"><?php _e( 'Edit' ); ?></span></a>
</span>
</div>
</div>
<div class="menu-item-settings wp-clearfix" id="menu-item-settings-<?php echo $item_id; ?>">
<?php if ( 'custom' == $item->type ) : ?>
<p class="field-url description description-wide">
<label for="edit-menu-item-url-<?php echo $item_id; ?>">
<?php _e( 'URL' ); ?><br />
<input type="text" id="edit-menu-item-url-<?php echo $item_id; ?>" class="widefat code edit-menu-item-url" name="menu-item-url[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->url ); ?>" />
</label>
</p>
<?php endif; ?>
<p class="field-xfn description description-thin">
<label for="edit-menu-item-xfn-<?php echo $item_id; ?>">
<?php _e( 'Link Relationship (XFN)' ); ?><br />
<input type="text" id="edit-menu-item-xfn-<?php echo $item_id; ?>" class="widefat code edit-menu-item-xfn" name="menu-item-xfn[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->xfn ); ?>" />
</label>
</p>
<?php
do_action( 'wp_nav_menu_item_custom_fields', $item_id, $item, $depth, $args );
?>
<fieldset class="field-move hide-if-no-js description description-wide">
<span class="field-move-visual-label" aria-hidden="true"><?php _e( 'Move' ); ?></span>
<button type="button" class="button-link menus-move menus-move-up" data-dir="up"><?php _e( 'Up one' ); ?></button>
<button type="button" class="button-link menus-move menus-move-down" data-dir="down"><?php _e( 'Down one' ); ?></button>
<button type="button" class="button-link menus-move menus-move-left" data-dir="left"></button>
<button type="button" class="button-link menus-move menus-move-right" data-dir="right"></button>
<button type="button" class="button-link menus-move menus-move-top" data-dir="top"><?php _e( 'To the top' ); ?></button>
</fieldset>
<div class="menu-item-actions description-wide submitbox">
<?php if ( 'custom' != $item->type && $original_title !== false ) : ?>
<p class="link-to-original">
<?php printf( __('Original: %s'), '' . esc_html( $original_title ) . '' ); ?>
</p>
<?php endif; ?>
<a class="item-delete submitdelete deletion" id="delete-<?php echo $item_id; ?>" href="<?php
echo wp_nonce_url(
add_query_arg(
array(
'action' => 'delete-menu-item',
'menu-item' => $item_id,
),
admin_url( 'nav-menus.php' )
),
'delete-menu_item_' . $item_id
); ?>"><?php _e( 'Remove' ); ?></a> <span class="meta-sep hide-if-no-js"> | </span> <a class="item-cancel submitcancel hide-if-no-js" id="cancel-<?php echo $item_id; ?>" href="<?php echo esc_url( add_query_arg( array( 'edit-menu-item' => $item_id, 'cancel' => time() ), admin_url( 'nav-menus.php' ) ) );
?>#menu-item-settings-<?php echo $item_id; ?>"><?php _e('Cancel'); ?></a>
</div>
<input class="menu-item-data-db-id" type="hidden" name="menu-item-db-id[<?php echo $item_id; ?>]" value="<?php echo $item_id; ?>" />
<input class="menu-item-data-object-id" type="hidden" name="menu-item-object-id[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->object_id ); ?>" />
<input class="menu-item-data-object" type="hidden" name="menu-item-object[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->object ); ?>" />
<input class="menu-item-data-parent-id" type="hidden" name="menu-item-parent-id[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->menu_item_parent ); ?>" />
<input class="menu-item-data-position" type="hidden" name="menu-item-position[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->menu_order ); ?>" />
<input class="menu-item-data-type" type="hidden" name="menu-item-type[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $item->type ); ?>" />
</div>
<ul class="menu-item-transport"></ul>
<?php
$output .= ob_get_clean();
}
}
As basic as the answer is, I'll leave the question active...
I had instantiated the class 2 times!
I need to configure this script so that it fetches the first image that is in the article and shows it in a widjet.
At the moment the widjet only shows featured images, I would like it to show external images that were in the post.
For example, the first image in the article would be shown.
Code
<?php
/**
* Featured Posts widget
*/
class colormag_featured_posts_widget extends WP_Widget {
function __construct() {
$widget_ops = array(
'classname' => 'widget_featured_posts widget_featured_meta',
'description' => __( 'Display latest posts or posts of specific category.', 'colormag' ),
'customize_selective_refresh' => true,
);
$control_ops = array( 'width' => 200, 'height' => 250 );
parent::__construct( false, $name = __( 'TG: Featured Posts (Style 1)', 'colormag' ), $widget_ops );
}
function form( $instance ) {
$tg_defaults['title'] = '';
$tg_defaults['text'] = '';
$tg_defaults['number'] = 4;
$tg_defaults['type'] = 'latest';
$tg_defaults['category'] = '';
$instance = wp_parse_args( ( array ) $instance, $tg_defaults );
$title = esc_attr( $instance['title'] );
$text = esc_textarea( $instance['text'] );
$number = $instance['number'];
$type = $instance['type'];
$category = $instance['category'];
?>
<p><?php _e( 'Layout will be as below:', 'colormag' ) ?></p>
<div style="text-align: center;"><img src="<?php echo get_template_directory_uri() . '/img/style-1.jpg' ?>">
</div>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'colormag' ); ?></label>
<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<?php _e( 'Description', 'colormag' ); ?>
<textarea class="widefat" rows="5" cols="20" id="<?php echo $this->get_field_id( 'text' ); ?>" name="<?php echo $this->get_field_name( 'text' ); ?>"><?php echo $text; ?></textarea>
<p>
<label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts to display:', 'colormag' ); ?></label>
<input id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="text" value="<?php echo $number; ?>" size="3" />
</p>
<p>
<input type="radio" <?php checked( $type, 'latest' ) ?> id="<?php echo $this->get_field_id( 'type' ); ?>" name="<?php echo $this->get_field_name( 'type' ); ?>" value="latest" /><?php _e( 'Show latest Posts', 'colormag' ); ?>
<br />
<input type="radio" <?php checked( $type, 'category' ) ?> id="<?php echo $this->get_field_id( 'type' ); ?>" name="<?php echo $this->get_field_name( 'type' ); ?>" value="category" /><?php _e( 'Show posts from a category', 'colormag' ); ?>
<br /></p>
<p>
<label for="<?php echo $this->get_field_id( 'category' ); ?>"><?php _e( 'Select category', 'colormag' ); ?>
:</label>
<?php wp_dropdown_categories( array(
'show_option_none' => ' ',
'name' => $this->get_field_name( 'category' ),
'selected' => $category,
) ); ?>
</p>
<?php
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
if ( current_user_can( 'unfiltered_html' ) ) {
$instance['text'] = $new_instance['text'];
} else {
$instance['text'] = stripslashes( wp_filter_post_kses( addslashes( $new_instance['text'] ) ) );
}
$instance['number'] = absint( $new_instance['number'] );
$instance['type'] = $new_instance['type'];
$instance['category'] = $new_instance['category'];
return $instance;
}
function widget( $args, $instance ) {
extract( $args );
extract( $instance );
global $post;
$title = isset( $instance['title'] ) ? $instance['title'] : '';
$text = isset( $instance['text'] ) ? $instance['text'] : '';
$number = empty( $instance['number'] ) ? 4 : $instance['number'];
$type = isset( $instance['type'] ) ? $instance['type'] : 'latest';
$category = isset( $instance['category'] ) ? $instance['category'] : '';
$post_status = 'publish';
if ( get_option( 'fresh_site' ) == 1 ) {
$post_status = array( 'auto-draft', 'publish' );
}
$args = array(
'posts_per_page' => $number,
'post_type' => 'post',
'ignore_sticky_posts' => true,
'no_found_rows' => true,
'post_status' => $post_status,
);
// Display from category chosen.
if ( $type == 'category' ) {
$args['category__in'] = $category;
}
$get_featured_posts = new WP_Query( $args );
echo $before_widget;
?>
<?php
if ( $type != 'latest' ) {
$border_color = 'style="border-bottom-color:' . colormag_category_color( $category ) . ';"';
$title_color = 'style="background-color:' . colormag_category_color( $category ) . ';"';
} else {
$border_color = '';
$title_color = '';
}
if ( ! empty( $title ) ) {
echo '<h3 class="widget-title" ' . $border_color . '><span ' . $title_color . '>' . esc_html( $title ) . '</span></h3>';
}
if ( ! empty( $text ) ) {
?> <p> <?php echo esc_textarea( $text ); ?> </p> <?php } ?>
<?php
$i = 1;
while ( $get_featured_posts->have_posts() ):$get_featured_posts->the_post();
?>
<?php if ( $i == 1 ) {
$featured = 'colormag-featured-post-medium';
} else {
$featured = 'colormag-featured-post-small';
} ?>
<?php if ( $i == 1 ) {
echo '<div class="first-post">';
} elseif ( $i == 2 ) {
echo '<div class="following-post">';
} ?>
<div class="single-article clearfix">
<?php
if ( has_post_thumbnail() ) {
$image = '';
$thumbnail_id = get_post_thumbnail_id( $post->ID );
$image_alt_text = get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true );
$title_attribute = get_the_title( $post->ID );
if ( empty( $image_alt_text ) ) {
$image_alt_text = $title_attribute;
}
$image .= '<figure>';
$image .= '<a href="' . get_permalink() . '" title="' . the_title( '', '', false ) . '">';
$image .= get_the_post_thumbnail( $post->ID, $featured, array(
'title' => esc_attr( $title_attribute ),
'alt' => esc_attr( $image_alt_text ),
) ) . '</a>';
$image .= '</figure>';
echo $image;
}
?>
<div class="article-content">
<?php colormag_colored_category(); ?>
<h3 class="entry-title">
<?php the_title(); ?>
</h3>
<div class="below-entry-meta">
<?php
$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
}
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
printf( __( '<span class="posted-on"><i class="fa fa-calendar-o"></i> %3$s</span>', 'colormag' ), esc_url( get_permalink() ), esc_attr( get_the_time() ), $time_string
);
?>
<span class="byline"><span class="author vcard"><i class="fa fa-user"></i><a class="url fn n" href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" title="<?php echo get_the_author(); ?>"><?php echo esc_html( get_the_author() ); ?></a></span></span>
<?php if ( ! post_password_required() && comments_open() ) { ?>
<span class="comments"><i class="fa fa-comment"></i><?php comments_popup_link( '0', '1', '%' ); ?></span>
<?php } ?>
</div>
<?php if ( $i == 1 ) { ?>
<div class="entry-content">
<?php the_excerpt(); ?>
</div>
<?php } ?>
</div>
</div>
<?php if ( $i == 1 ) {
echo '</div>';
} ?>
<?php
$i ++;
endwhile;
if ( $i > 2 ) {
echo '</div>';
}
// Reset Post Data
wp_reset_query();
?>
<!-- </div> -->
<?php
echo $after_widget;
}
}
This is the complete code of the widget
Try this code
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')">
</div>
<?php endif; ?>
I am getting this error
Trying to get property of non-object in /wp-includes/post-template.php
Others have suggested using wp_reset_postdata() to fix the issue however, it doesnt seem to work.
I have the code from the post-template.php below:
// If post password required and it doesn't match the cookie.
if ( post_password_required( $post ) )
return get_the_password_form( $post );
if ( $page > count( $pages ) ) // if the requested page doesn't exist
$page = count( $pages ); // give them the highest numbered page that DOES exist
$content = $pages[$page - 1];
if ( preg_match( '/<!--more(.*?)?-->/', $content, $matches ) ) {
$content = explode( $matches[0], $content, 2 );
if ( ! empty( $matches[1] ) && ! empty( $more_link_text ) )
$more_link_text = strip_tags( wp_kses_no_null( trim( $matches[1] ) ) );
$has_teaser = true;
} else {
$content = array( $content );
}
if ( false !== strpos( $post->post_content, '<!--noteaser-->' ) && ( ! $multipage || $page == 1 ) )
$strip_teaser = true;
$teaser = $content[0];
if ( $more && $strip_teaser && $has_teaser )
$teaser = '';
$output .= $teaser;
Here are my post functions/queries
function my_header_add_to_cart_fragment( $fragments ) {
ob_start();
$count = WC()->cart->cart_contents_count;
?><a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php
if ( $count > 0 ) {
?>
<span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
<?php
}
?></a><?php
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment' );
function global_menu($location,$class){
wp_nav_menu( array(
'theme_location' => $location,//primary
'depth' => 2, // 1 = no dropdowns, 2 = with dropdowns.
'container' => null,
'menu_class' => $class,//navbar-nav mr-auto
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker(),
) );
}
add_filter( 'menu-init', 'global_menu' );
function portal_cart_link($url) {
?>
<a class="cart-contents" href="<?php echo $url; ?>" title="<?php esc_attr_e( 'View your shopping cart', permaslug() ); ?>">
<span class="cart-contents-count"><?php echo WC()->cart->get_cart_contents_count();?></span>
</a>
<?php
}
add_filter( 'woo-init', 'portal_cart_link' );
function product_query() {
$args = array(
'post_type' => 'product',
);
$loop = new WP_Query( $args );
if($loop->have_posts()):while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<div class="col-md-3 product"><img class="img-responsive" src="' . get_the_post_thumbnail_url( $post->ID) .'" /><br /><h3 class="text-center">' . get_the_title() . '</h3></div>';
endwhile;endif;
wp_reset_postdata();
}
add_filter( 'woo-init', 'product_query' );
Trying to build a widget for my simple wordpress blog, which will display categories in the sidebar, but not exactly like the native wordpress category widget. Basically, what I am trying to achieve is to be able to mark certain categories as "New!" or something similar, but from within the widget itself.
So far I have the following code that registers my widget and can display categories list in it on the backend with checkbox next to the name.
When I check the box and trying to save it it returns unchecked again. Not sure if my update function is actually working as serialized array in the DB has not changed on save.
Here is what I have do far:
/* CUSTOM BLOG CATEGORIES WIDGETS */
class Spr123_Categories_Widget extends WP_Widget {
public function __construct() {
$widget_options = array(
'classname' => 'widget_custom_categories_widget',
'description' => 'This is a Custom Blog Categories Widget',
);
parent::__construct( 'custom_categories_widget', 'Custom Categories Widget', $widget_options );
}
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
$name = ! empty( $instance['name'] ) ? $instance['name'] : '';
$checked = isset( $instance['checked'] ) ? (bool) $instance['checked'] : false;
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0,
"hide_empty" => 0,
) );
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
<input type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" class="widefat" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
</p>
<p>
<label for="Categories">Categories:</label>
</p>
<?php print("<pre>".print_r($categories,true)."</pre>"); ?>
<p>
<?php
foreach ( $categories as $category ) {
?>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id($category->slug); ?>" name="<?php echo $this->get_field_name('checked'); ?>"<?php checked( $checked ); ?> />
<label for="<?php echo $this->get_field_id($category->slug); ?>"><?php _e( 'Display as NEW - ' . esc_attr( $category->name )); ?></label><br />
<?php
}
?>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
$instance[ 'name' ] = strip_tags( $new_instance[ 'name' ] );
$instance[ 'checked' ] = !empty($new_instance['checked']) ? 1 : 0;
return $instance;
}
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance[ 'title' ] );
$category_title = apply_filters( 'widget_title', $instance[ 'name' ] );
echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title']; ?>
<p><?php echo $category_title ?></p>
<?php echo $args['after_widget'];
}
}
function spr123_custom_categories_widget() {
register_widget( 'Spr123_Categories_Widget' );
}
add_action( 'widgets_init', 'spr123_custom_categories_widget' );
Try this code
/* CUSTOM BLOG CATEGORIES WIDGETS */
class Spr123_Categories_Widget extends WP_Widget {
public function __construct() {
$widget_options = array(
'classname' => 'widget_custom_categories_widget',
'description' => 'This is a Custom Blog Categories Widget',
);
parent::__construct( 'custom_categories_widget', 'Custom Categories Widget', $widget_options );
}
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
$name = ! empty( $instance['name'] ) ? $instance['name'] : '';
$checked = isset( $instance['checked'] ) ? (bool) $instance['checked'] : false;
$savedcategories = ! empty( $instance['categories'] ) ? $instance['categories'] : '';
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0,
"hide_empty" => 0,
) );
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
<input type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" class="widefat" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
</p>
<p>
<label for="Categories">Categories:</label>
</p>
<!-- --><?php //print("<pre>".print_r($categories,true)."</pre>"); ?>
<p>
<?php
foreach ( $categories as $category ) {
$checked = in_array($category->term_id, $savedcategories)?'checked':'';
?>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id($category->slug); ?>" name="<?php echo $this->get_field_name('categories[]'); ?>" <?php echo $checked; ?> value="<?php echo $category->term_id; ?>"/>
<label for="<?php echo $this->get_field_id($category->slug); ?>"><?php echo esc_attr( $category->name ) . _e( 'Display as NEW - ' ); ?></label><br />
<?php
}
?>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
$instance[ 'name' ] = strip_tags( $new_instance[ 'name' ] );
$instance[ 'categories' ] = $new_instance['categories'];
return $instance;
}
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance[ 'title' ] );
$category_title = apply_filters( 'widget_title', $instance[ 'name' ] );
echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title']; ?>
<p><?php echo $category_title ?></p>
<?php echo $args['after_widget'];
}
}
function spr123_custom_categories_widget() {
register_widget( 'Spr123_Categories_Widget' );
}
add_action( 'widgets_init', 'spr123_custom_categories_widget' );
you can the value in frontend by using this code
$widget_instances = get_option('widget_custom_categories_widget');
print_r($widget_instances);
So this is my first attempt a creating a widget that has a functionality of creating a simple image rollover effect (if anyone wants it when it's done, leave me a message).
Now I downloaded a sample widget and made some changes, I still haven't touched the html part for the output so ignore that bit. Now my problem is, when I click save, the values in the fields go back to their default values, and they did not do this on the sample widget. Here's my code:
<?php
/**
* Plugin Image: Rollover Widget
* Description: A widget that creates a rollover image effect with a hyperlink.
* Version: 0.1
* Author: Zak Elas
* Author URI:
*/
add_action( 'widgets_init', 'my_widget' );
function my_widget() {
register_widget( 'MY_Widget' );
}
class MY_Widget extends WP_Widget {
function MY_Widget() {
$widget_ops = array( 'classname' => 'example', 'description' => __('A widget that creates a rollover image effect with a hyperlink. ', 'example') );
$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'Rollover Widget' );
$this->WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops );
}
function widget( $args, $instance ) {
extract( $args );
//Our variables from the widget settings.
$link = apply_filters('widget_link', $instance['link'] );
$image = $instance['image'];
$rollover_image = $instance['rollover_image'];
echo $before_widget;
// Display the widget link
if ( $link )
echo $before_link . $link . $after_link;
//Display the name
printf( '<p>' . __('Hey their Sailor! My name is %1$s.', 'example') . '</p>', $image );
printf( '<p>' . __('Hey their Sailor! My name is %1$s.', 'example') . '</p>', $rollover_image );
echo $after_widget;
}
//Update the widget
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
//Strip tags from link and name to remove HTML
$instance['link'] = strip_tags( $new_instance['link'] );
$instance['image'] = strip_tags( $new_instance['image'] );
$instance['rollover_image'] = strip_tags( $new_instance['rollover_image'] );
return $instance;
}
function form( $instance ) {
//Set up some default widget settings.
$defaults = array( 'link' => __('Example', 'example'), 'image' => __('/images/editorial.png', 'example') , 'rollover_image' => __('/images/editorial.png', 'example') );
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<p>
<label for="<?php echo $this->get_field_id( 'link' ); ?>"><?php _e('link', 'example'); ?></label>
<input id="<?php echo $this->get_field_id( 'link' ); ?>" name="<?php echo $this->get_field_name( 'link' ); ?>" value="<?php echo $instance['link']; ?>" style="width:100%;" />
</p>
<p>
<label for="<?php echo $this->get_field_id( 'image' ); ?>"><?php _e('image', 'example'); ?></label>
<input id="<?php echo $this->get_field_id( 'image' ); ?>" name="<?php echo $this->get_field_name( 'image' ); ?>" value="<?php echo $instance['image']; ?>" style="width:100%;" />
</p>
<p>
<label for="<?php echo $this->get_field_id( 'rollover_image' ); ?>"><?php _e('rollover_image:', 'example'); ?></label>
<input id="<?php echo $this->get_field_id( 'rollover_image' ); ?>" name="<?php echo $this->get_field_name( 'image' ); ?>" value="<?php echo $instance['rollover_image']; ?>" style="width:100%;" />
</p>
<?php
}
}
?>
And here is the sample widgets code
<?php
/**
* Plugin Name: A simple Widget
* Description: A widget that displays authors name.
* Version: 0.1
* Author: Bilal Shaheen
* Author URI: http://gearaffiti.com/about
*/
add_action( 'widgets_init', 'my_widget' );
function my_widget() {
register_widget( 'MY_Widget' );
}
class MY_Widget extends WP_Widget {
function MY_Widget() {
$widget_ops = array( 'classname' => 'example', 'description' => __('A widget that displays the authors name ', 'example') );
$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' );
$this->WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops );
}
function widget( $args, $instance ) {
extract( $args );
//Our variables from the widget settings.
$title = apply_filters('widget_title', $instance['title'] );
$name = $instance['name'];
$show_info = isset( $instance['show_info'] ) ? $instance['show_info'] : false;
echo $before_widget;
// Display the widget title
if ( $title )
echo $before_title . $title . $after_title;
//Display the name
if ( $name )
printf( '<p>' . __('Hey their Sailor! My name is %1$s.', 'example') . '</p>', $name );
if ( $show_info )
printf( $name );
echo $after_widget;
}
//Update the widget
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
//Strip tags from title and name to remove HTML
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['name'] = strip_tags( $new_instance['name'] );
$instance['show_info'] = $new_instance['show_info'];
return $instance;
}
function form( $instance ) {
//Set up some default widget settings.
$defaults = array( 'title' => __('Example', 'example'), 'name' => __('Bilal Shaheen', 'example'), 'show_info' => true );
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
//Widget Title: Text Input.
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'example'); ?></label>
<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" />
</p>
//Text Input.
<p>
<label for="<?php echo $this->get_field_id( 'name' ); ?>"><?php _e('Your Name:', 'example'); ?></label>
<input id="<?php echo $this->get_field_id( 'name' ); ?>" name="<?php echo $this->get_field_name( 'name' ); ?>" value="<?php echo $instance['name']; ?>" style="width:100%;" />
</p>
//Checkbox.
<p>
<input class="checkbox" type="checkbox" <?php checked( $instance['show_info'], true ); ?> id="<?php echo $this->get_field_id( 'show_info' ); ?>" name="<?php echo $this->get_field_name( 'show_info' ); ?>" />
<label for="<?php echo $this->get_field_id( 'show_info' ); ?>"><?php _e('Display info publicly?', 'example'); ?></label>
</p>
<?php
}
}
?>
The id_base should match the first argument for WP_Widget, and it should be lower case, no spaces:
$control_ops = array(
'width' => 300,
'height' => 350,
'id_base' => 'rollover_image_id'
);
$this->WP_Widget(
'rollover_image_id',
__('Example Widget', 'example'),
$widget_ops,
$control_ops
);
And you have a get_field_name( 'image' )
where it should be get_field_name( 'rollover_image' ).
Change this line
$this->WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops );
to this
$this->WP_Widget( 'my_widget', __('Example Widget', 'example'), $widget_ops, $control_ops );
consructor id (which was example-widget and I have corected to my_widget) must be namespaced form (lowercase, nospace) of class name (which is MY_Widget).
This will work insaAllah.