edit my get first image function - wordpress

in my wp_theme i have this function to get first image of post as thumbnail
function get_first_image() {
global $post;
$first_img = '';
preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', do_shortcode( $post->post_content, 'gallery' ), $matches );
$first_img = isset( $matches[1][0] ) ? $matches[1][0] : null;
if ( empty( $first_img ) ) {
return get_template_directory_uri() . '/assets/images/empty.png'; // path to default image.
}
// Now we have the $first_img but we want the thumbnail of that image.
$explode = explode( '.', $first_img );
$count = count( $explode );
$size = '-150x150'; // Our panel ratio (2:1) 312x156 for lighther page, 624x312 for retina; use add_image_size() and Force Regenerate Thumbnails plugin when changing sizes.
$explode[ $count -2 ] = $explode[ $count -2 ] . '' . $size;
$thumb_img = implode( '.', $explode );
return $thumb_img;}
but some image have custome size and this function not work on this case
like this :
https://yawar.ir/wp-content/uploads/2014/08/yawar-1024x682.jpg
how can i force change the url of images that have another size ?

The WP codex page regarding thumbnails says that you can specify your own sizes: https://codex.wordpress.org/Post_Thumbnails Look under "Add New Post Thumbnail Sizes". Maybe that will point you in the right direction.
Other than that, what about not specifying the size at all? Then maybe the browser would display the image at its natural size?

Related

Active Image size Woocommerce Product page

Hi guys I have a problem. On my product page the active image has the same size of thumbnail, I don't know what happened. Take a look https://www.extrasocial.it/instagram-followers-reali/
You may need to find out by deactivating other plugin. For time being you can use this code snippet in your active theme functions.php
add_filter( 'wp_get_attachment_image_src', array( $this, 'pn_change_product_image_link'), 50, 4 );
function pn_change_product_image_link( $image, $attachment_id, $size, $icon ){
if( ! is_product() ) return $image; //if not product page
if( $size == 'shop_thumbnail' ) return $image; // if not gallery thumbnails
// Your source image link
$src = wp_get_attachment_url( $attachment_id );
$width = ''; // define the width if needed
$height = ''; // define the height if needed
$image = array( $src, $width, $height );
return $image;
}
I've found the solution, it was a plugin (Fast Velocity Minify). Once deactivated, everything came back to normal. Thank you Mujeebu.

Hook in to post_gallery function to change the styles of gallery

I have a problem that drives me mad, and can't find a solution to it in the documentation...
I want to hook in to Wordpress' post_gallery function to add a Class to the dl element that wraps the WP generated gallery individual images. By this I want to have the option to have full width images that can be controlled in the Attachments window of WP Media via ACF switch
if ( get_field('fullwidth') == 1 ){
$classname = 'fullwidth';
} else {
$classname = "";
}
Also setting the img "src" to the Large for these fullwidth images would come handy, so the page-load is not too slow.
Do I need to rewrite the whole gallery generating code from here?
https://core.trac.wordpress.org/browser/trunk/src/wp-includes/media.php
Can it be done via this method at all, or should I somehow try to hook in to the_content? But also for that method, I didn't find any info in regard how galleries are generated...
to add a Class to the dl element that wraps the WP generated gallery individual images
Instead of that, why don't you — using the Text/HTML editor — add the gallery like this:
<div class="fullwidth">
[gallery ... /]
</div>
(the three dots indicates the Shortcode parameters such as ids, size, and link)
And write some CSS code similar to:
.fullwidth .gallery-item {
/* Add styles for the DL (or FIGURE for HTML5-supported themes) element that wraps the gallery image and caption. */
}
.fullwidth .gallery-icon {
/* Add styles for the DT (or DIV for HTML5-supported themes) element that wraps the gallery image. */
}
.fullwidth .gallery-caption {
/* Add styles for the DD (or FIGCAPTION for HTML5-supported themes) element that wraps the gallery caption. */
}
[EDIT] Below is a custom Shortcode; used the exact same way you'd use the default [gallery] Shortcode.
Add these to the theme's functions.php file:
/**
* #param array $attr
* #param WP_Post $attachment
*/
function gallery_shortcode2_image_attributes( $attr, $attachment ) {
// Name of the custom field. (ACF)
$field_name = 'fullwidth';
if ( get_field( $field_name, $attachment->ID ) ) {
$attr['data-gallery-layout'] = 'full-width';
}
return $attr;
}
add_shortcode( 'gallery2', 'gallery_shortcode2' );
function gallery_shortcode2( $attr ) {
$atts = shortcode_atts( array(
'itemtag' => 'figure', // I'm assuming we'll always be using HTML5-supported themes..
'fwclass' => 'fullwidth', // The CSS class applied to items with, well, full-width layout.
'size' => 'medium_large', // You may change the default value; to "large", "custom", etc.
), $attr );
// Don't modify anything below unless you're 100% sure of what you're doing. =)
$itemtag = tag_escape( $atts['itemtag'] );
$valid_tags = wp_kses_allowed_html( 'post' );
if ( ! isset( $valid_tags[ $itemtag ] ) ) {
$itemtag = 'dl';
}
add_filter( 'wp_get_attachment_image_attributes', 'gallery_shortcode2_image_attributes', 10, 2 );
$output = gallery_shortcode( array_merge( $attr, $atts ) );
$output2 = '';
remove_filter( 'wp_get_attachment_image_attributes', 'gallery_shortcode2_image_attributes', 10, 2 );
$_tag = '<' . preg_quote( $itemtag ) . ' class=\'gallery-item\'>';
$arr = preg_split( "/($_tag)/", $output, -1, PREG_SPLIT_DELIM_CAPTURE );
for ( $i = 0, $j = 1; $i < count( $arr ); $i++, $j++ ) {
if ( $_tag === $arr[ $i ] && isset( $arr[ $j ] ) ) {
$class = 'gallery-item';
if ( preg_match( '/<img (.*?) data-gallery-layout="full-width"/', $arr[ $j ] ) ) {
$class .= ' ' . $atts['fwclass'];
}
$output2 .= '<' . $itemtag . ' class=\'' . esc_attr( $class ) . '\'>';
} else {
$output2 .= $arr[ $i ];
}
}
unset( $output, $arr );
return $output2;
}
And use [gallery2] instead of [gallery]; same arguments (e.g. ids and size), but with one extra argument for [gallery2], which is fwclass. (Refer to the gallery_shortcode() function for details on that argument.)
Hopefully [gallery2] works for you, like it did for me.
NOTE: Use [gallery2] only if you want to add a custom CSS class to the individual gallery item element (i.e. .gallery-item). Otherwise, use the default Shortcode — [gallery].

Wordpress -- add description below to featured image

I would like to add an annotation below featured image box in post page ,saying
'Recommended image size: 1300px (width) x 340px (height)
Is it possible in wordpress 4.2.2.
The text is for the admin user for a better guidance.
Any help is highly appreciated. Thanks in advance.
Old post here, but I was trying to do this as well. A filter since WordPress 2.9.0 offers this capacity, like so:
/**
* Filters the admin post thumbnail HTML markup to return.
*
* #since 2.9.0
* #since 3.5.0 Added the `$post_id` parameter.
* #since 4.6.0 Added the `$thumbnail_id` parameter.
*
* #param string $content Admin post thumbnail HTML markup.
* #param int $post_id Post ID.
* #param int $thumbnail_id Thumbnail ID.
*/
return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID, $thumbnail_id );
So use it like this:
function stackoverflow_30817906( $content, $post_id, $thumbnail_id ) {
if ( 'post' !== get_post_type( $post_id ) ) {
return $content;
}
$caption = '<p>' . esc_html__( 'Recommended image size: 1300px (width) x 340px (height)', 'i18n-tag' ) . '</p>';
return $content . $caption;
}
add_filter( 'admin_post_thumbnail_html', 'stackoverflow_30817906', 10, 3 );
If you want to do this without editing core files you could just use jQuery to add the text.
add_action('admin_footer', function() {
global $pagenow;
if('post.php' == $pagenow || 'post-new.php' == $pagenow) : ?>
<script>
jQuery(document).ready(function($) {
$('#postimagediv .inside').after('<div style="padding: 0 12px 12px;">Recommended image size: 1300px (width) x 340px (height)</div>');
});
</script>
<?php endif;
});
This solution isn't as 'clean' as making the change directly in the PHP file, but I think it is preferable to editing the core. With this solution you don't have to worry about remaking the change after a WordPress update.
You should go to wp-admin->includes->post.php
and around line 1295 (depending on version) you will find:
if ( !empty( $thumbnail_html ) ) {
$ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
$content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html );
$content .= '<p class="hide-if-no-js">' . esc_html__( 'Remove featured image' ) . '</p>';
}
change it to:
if ( !empty( $thumbnail_html ) ) {
$ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
$content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html );
$content .= '<p class="hide-if-no-js">' . esc_html__( 'Remove featured image' ) . '<span style="display:block;">Recommended image size: 1300px (width) x 340px (height)</span></p>';
}
It is not recommended to change core files as your changes can be lost during the update, but I don't recommend creating a plugin just for this small change.

Size of featured image in admin panel?

Been experimenting with some custom meta boxes, but nothing I've read or can find is helping me to achieve what I'm actually after.
I can render a new meta box, but I can't find a way to actually change the output of the post thumbnail itself in the admin panel.
function new_post_thumbnail_meta_box() {
global $post;
echo 'Content above the image.';
$thumbnail_id = get_post_meta( $post->ID, '_thumbnail_id', true );
echo _wp_post_thumbnail_html( $thumbnail_id );
echo 'Content below the image.';
}
function render_new_post_thumbnail_meta_box() {
global $post_type;
// remove the old meta box
remove_meta_box( 'postimagediv','post','side' );
// adding the new meta box.
add_meta_box('postimagediv', __('Featured Image'), 'new_post_thumbnail_meta_box', $post_type, 'side', 'low');
}
add_action('do_meta_boxes', 'render_new_post_thumbnail_meta_box');
How to have a larger or 'actual size' version of the featured image displayed in the administration panel?
Copied the includes function and modified the output, this throws up a server error.
function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
global $content_width, $_wp_additional_image_sizes;
$post = get_post( $post );
$upload_iframe_src = esc_url( get_upload_iframe_src('image', $post->ID ) );
$set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set featured image' ) . '" href="%s" id="set-post-thumbnail" class="thickbox">%s</a></p>';
$content = sprintf( $set_thumbnail_link, $upload_iframe_src, esc_html__( 'Set featured image' ) );
if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
$old_content_width = $content_width;
$content_width = 600;
if ( !isset( $_wp_additional_image_sizes['post-thumbnail'] ) )
$thumbnail_html = wp_get_attachment_image( $thumbnail_id, array( $content_width, $content_width ) );
else
$thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'post-thumbnail' );
if ( !empty( $thumbnail_html ) ) {
$ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
$content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html );
$content .= '<p class="hide-if-no-js">' . esc_html__( 'Remove featured image' ) . '</p>';
}
$content_width = $old_content_width;
}
return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID );
}
Or should I be using add_image_size( 'post_thumbnail', 600, 400, true ); ? since that's what it looks for?
Just in case somebody is stumbling on this old post.
WP introduced a new filter called admin_post_thumbnail_size for you to be able to change the default image size in the admin panel.
To change the size of the featured thumbnail image you can use something like this:
function custom_admin_thumb_size($thumb_size){
return "custom-image-size"; //or use something like array(400,400).
}
add_filter( 'admin_post_thumbnail_size', 'custom_admin_thumb_size');
You should replace _wp_post_thumbnail_html with get_the_post_thumbnail
Starting in WordPress 4.4, a new filter was introduced, admin_post_thumbnail_size, which allows for modifying the display size of the post thumbnail image in the Featured Image meta box.
When a theme adds ‘post-thumbnail’ support, a special ‘post-thumbnail’ image size is registered, which differs from the ‘thumbnail’ image size managed via the Settings > Media screen.
We can use this filter to alter the post-thumbnail size (266 x 266 px) and modify it to use the default thumbnail size (150 x 150 px) instead.
/**
* Change Display Size of Featured Image Thumbnail in WordPress Admin Dashboard
*/
add_filter( 'admin_post_thumbnail_size', function ( $size, $thumbnail_id, $post ) {
$sizes = get_intermediate_image_sizes();
$result = array_search( 'thumbnail', $sizes );
$size = is_numeric( $result ) ? $sizes[ $result ] : array( 100, 100 );
return $size;
}, 10, 3 );
A specific size (e.g., 100 x 100 px) can also be specified or set as a fallback in case the intermediate thumbnail size isn't available.
The function _wp_post_thumbnail_html returns a code like this:
<p class="hide-if-no-js">
<a title="Set featured image" href="http://example.com/wp-admin/media-upload.php?post_id=4573&type=image&TB_iframe=1" id="set-post-thumbnail" class="thickbox">
<img width="266" height="90" src="http://example.com/wp-content/uploads/thumb2-3-846x288.png" class="attachment-post-thumbnail" alt="thumb2-3" />
</a>
</p>
<p class="hide-if-no-js">
<a href="#" id="remove-post-thumbnail" onclick="WPRemoveThumbnail('dfd8f3353b');return false;">
Remove featured image
</a>
</p>
Note that the image is 846x288, but it's being resized to 266x90 in the img tag attributes.
Analyzing the function, we see that if there is an image size named post_thumbnail, it will get that one. Otherwise, it gets an image size of 266x266 (with crop). You can simply copy the function and modify to your desired output.
Other option is to use the filter admin_post_thumbnail_html and remove the img width and height attributtes:
add_filter( 'admin_post_thumbnail_html', 'filter_featured_img_so_17713997' );
function filter_featured_img_so_17713997( $html )
{
$doc = new DOMDocument();
$doc->loadHTML($html);
$tags = $doc->getElementsByTagName('img');
if(count($tags) > 0)
{
$tag = $tags->item(0);
$tag->removeAttribute('width');
$tag->removeAttribute('height');
return $doc->saveHTML($tag);
}
return $html;
}
The results may not be what you expect, though. If the image is larger than 266, it bleeds out of the browser canvas.
Here's another option to use a custom sized thumbnail or the system defined 'full' sized image (the original size of the image you uploaded) as the Featured Image displayed in the admin panel:
/**
* step 1 - define custom image size
*
* - either plan to use 'full' (returns the size of the image you uploaded) OR define our custom image size
* - so we can call one of those instead of the system defined default 'post-thumbnail'
*
* - remainder of this example assumes using a custom image size, so it is defined
* - if using 'full', instead, then no need to define custom
* - so remove the following add_image_size line (and thereby skip step 1)
*/
add_image_size( 'admin-post-thumbnail', 846, 288, true );
/**
* step 2 - replace the meta box with ours for standard post type only, especially so we can set our own callback and
* - move it into the larger main column.
* - Note that in any event, the full size won't ever have greater width than the current column width
* - as CSS and modern admin panel make the image elements responsive to the column width.
*/
add_action('do_meta_boxes', 'so17713997_move_meta_box');
function so17713997_move_meta_box(){
remove_meta_box( 'postimagediv', 'post', 'side' );
add_meta_box('postimagediv', __('Featured Image'), 'so17713997_post_thumbnail_meta_box', 'post', 'normal', 'low');
}
// step 3 - custom callback to call our functional replacement for _wp_post_thumbnail_html for post type only
function so17713997_post_thumbnail_meta_box( $post ) {
$thumbnail_id = get_post_meta( $post->ID, '_thumbnail_id', true );
echo so17713997_wp_post_thumbnail_html( $thumbnail_id, $post->ID );
}
/**
* step 4 - replace _wp_post_thumbnail_html with our version that calls our thumbnail 'admin-post-thumbnail' instead of the default 'post-thumbnail'
*
* - we could do more here, like adjust the content width variable, but not entirely necessary. The custom image size we defined will
* - handle most of it, plus the admin section these days has responsive CSS, so the image doesn't blow-out column width in any event.
*/
function so17713997_wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
global $content_width, $_wp_additional_image_sizes;
$post = get_post( $post );
$post_type_object = get_post_type_object( $post->post_type );
$set_thumbnail_link = '<p class="hide-if-no-js"><a title="%s" href="%s" id="set-post-thumbnail" class="thickbox">%s</a></p>';
$upload_iframe_src = get_upload_iframe_src( 'image', $post->ID );
$content = sprintf( $set_thumbnail_link,
esc_attr( $post_type_object->labels->set_featured_image ),
esc_url( $upload_iframe_src ),
esc_html( $post_type_object->labels->set_featured_image )
);
if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
$old_content_width = $content_width;
$content_width = 266;
if ( !isset( $_wp_additional_image_sizes['admin-post-thumbnail'] ) ) // use our custom image size instead of 'post-thumbnail' OR use 'full' for system defined fullsize image
$thumbnail_html = wp_get_attachment_image( $thumbnail_id, array( $content_width, $content_width ) );
else
$thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'admin-post-thumbnail' ); // use our custom image size instead of 'post-thumbnail' OR use 'full' for system defined fullsize image
if ( !empty( $thumbnail_html ) ) {
$ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
$content = sprintf( $set_thumbnail_link,
esc_attr( $post_type_object->labels->set_featured_image ),
esc_url( $upload_iframe_src ),
$thumbnail_html
);
$content .= '<p class="hide-if-no-js">' . esc_html( $post_type_object->labels->remove_featured_image ) . '</p>';
}
$content_width = $old_content_width;
}
/**
* Filter the admin post thumbnail HTML markup to return.
*
* #since 2.9.0
*
* #param string $content Admin post thumbnail HTML markup.
* #param int $post_id Post ID.
*/
return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID );
}
Note first that the feature image selected may not reflect the updated size until after the post has been Saved or Updated, as appropriate.
Also, this hack makes extensive use of the following core WordPress functions:
the_post_thumbnail(),
add_meta_box(),
post_thumbnail_meta_box(), and
_wp_post_thumbnail_html
(I didn't have enough reputation yet to post more than two links, so google them.)
Have you tried changing the default Featured Image size by using set_post_thumbnail_size()? I had the same issue and this worked perfectly.
The WordPress Block editor shows Featured Images using square thumbnails by default. To change that, we need to apply a JavaScript filter instead of a PHP filter. A very simple filter to display uncropped Featured Images looks like this:
wp.hooks.addFilter(
"editor.PostFeaturedImage.imageSize",
"uncroppedFeaturedImage",
() => "post-thumbnail"
);
Load that script from the enqueue_block_editor_assets hook. Other registered image sizes (medium, large, etc.) can also be used.

Wordpress remove shortcode and save for use elsewhere

Trying to remove the gallery shortcode from the post content and save in a variable for use elsewhere in the template. The new Wordpress gallery tool is great for selecting which images they want and assigning captions, hoping to use this to create the gallery, but then pull it out of the content on the front-end.
So this little snipped works just fine for removing the gallery and reapplying formatting... however I want to save that gallery shortcode.
$content = strip_shortcodes( get_the_content() );
$content = apply_filters('the_content', $content);
echo $content;
Hoping to save the shortcode so it can be parsed into an array and used to recreate a custom gallery setup on the front-end. An example of this shortcode I'm trying to save is...
[gallery ids="1079,1073,1074,1075,1078"]
Any suggestions would be greatly appreciated.
Function to grab First Gallery shortcode from post content:
// Return first gallery shortcode
function get_shortcode_gallery ( $post = 0 ) {
if ( $post = get_post($post) ) {
$post_gallery = get_post_gallery($post, false);
if ( ! empty($post_gallery) ) {
$shortcode = "[gallery";
foreach ( $post_gallery as $att => $val ) {
if ( $att !== 'src') {
if ( $att === 'size') $val = "full"; // Set custom attribute value
$shortcode .= " ". $att .'="'. $val .'"'; // Add attribute name and value ( attribute="value")
}
}
$shortcode .= "]";
return $shortcode;
}
}
}
// Example of how to use:
echo do_shortcode( get_shortcode_gallery() );
Function to delete First gallery shortcode from Post content:
// Deletes first gallery shortcode and returns content
function strip_shortcode_gallery( $content ) {
preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );
if ( ! empty( $matches ) ) {
foreach ( $matches as $shortcode ) {
if ( 'gallery' === $shortcode[2] ) {
$pos = strpos( $content, $shortcode[0] );
if ($pos !== false)
return substr_replace( $content, '', $pos, strlen($shortcode[0]) );
}
}
}
return $content;
}
// Example of how to use:
$content = strip_shortcode_gallery( get_the_content() ); // Delete first gallery shortcode from post content
$content = str_replace( ']]>', ']]>', apply_filters( 'the_content', $content ) ); // Apply filter to achieve the same output that the_content() returns
echo $content;
just use the get_shortcode_regex():
<?php
$pattern = get_shortcode_regex();
preg_match_all('/'.$pattern.'/s', $post->post_content, $shortcodes);
?>
that will return an array of all the shortcodes in your content, which you can then output wherever you feel, like so:
<?php
echo do_shortcode($shortcodes[0][1]);
?>
similarly, you could use the array entries to check for shortcodes in your content and remove them with str_replace():
<?php
$content = $post->post_content;
$content = str_replace($shortcodes[0][1],'',$content);
?>
Something like $gallery = do_shortcode('[gallery]'); might work.

Resources