Remove featured image from the WooCommerce gallery - php

I tried using suggestions from other posts but they do not work. I am looking to not show the featured product image in my product images area/image gallery because I am using the featured image in the header as a background image and its too wide to be in the gallery.
So far this is the closest thing to working but I get an error. It does however do what I need.
Any way to fix this so i do not get the error?
Here is my code:
add_filter('woocommerce_single_product_image_thumbnail_html', 'remove_featured_image', 10, 3);
function remove_featured_image($html, $attachment_id, $post_id) {
$featured_image = get_post_thumbnail_id($post_id);
if ($attachment_id != $featured_image) {
return $html;
}
return '';
}
And here is the error:
Missing argument 3 for remove_featured_image() in /home/…/plugins/my-custom-functions/inc/php/functional.php(93) : eval()'d code on line 4
Warning: Missing argument 3 for remove_featured_image() in /home…/plugins/my-custom-functions/inc/php/functional.php(93) : eval()'d code on line 4

There is only 2 arguments for woocommerce_single_product_image_thumbnail_html filter hook.
So you have to change a little bit your code to avoid the error, this way:
add_filter('woocommerce_single_product_image_thumbnail_html', 'remove_featured_image', 10, 2);
function remove_featured_image($html, $attachment_id ) {
global $post, $product;
$featured_image = get_post_thumbnail_id( $post->ID );
if ( $attachment_id == $featured_image )
$html = '';
return $html;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
References for filter hook woocommerce_single_product_image_thumbnail_html:
woocommerce templates: single-product/product-image.php
woocommerce templates: single-product/product-thumbnails.php

This is what I did, hope it's helpful.
I used the Meta Box plugin to create a custom checkbox in the product edit page (in the Wordpress backend). The checkbox is basically "Hide featured image from product gallery" and here's the code (to be placed in the functions.php file):
function hide_first_img( $meta_boxes ) {
$prefix = 'meta_box';
$meta_boxes[] = array(
'id' => 'hide_img',
'title' => esc_html__( 'Hide first image', 'custom_meta_boxes' ),
'post_types' => array('product'),
'context' => 'advanced',
'priority' => 'default',
'autosave' => 'false',
'fields' => array(
array(
'id' => $prefix . '_hide_first_image',
'name' => esc_html__( 'Hide first image in product gallery', 'custom_meta_boxes' ),
'type' => 'checkbox',
'desc' => esc_html__( 'Check to hide the first image in the gallery', 'custom_meta_boxes' ),
),
),
);
return $meta_boxes;
}
add_filter( 'rwmb_meta_boxes', 'hide_first_img' );
Then I used LoicTheAztec's code, which works great, to remove the image ONLY if the checkbox is checked, like this (to be placed in the functions.php file):
function remove_featured_image($html, $attachment_id ) {
if( rwmb_meta( 'meta_box_hide_first_image' )){
global $post, $product;
$featured_image = get_post_thumbnail_id( $post->ID );
if ( $attachment_id == $featured_image )
$html = '';
}
return $html;
}
add_filter('woocommerce_single_product_image_thumbnail_html', 'remove_featured_image', 10, 2);
Finally, only for FLATSOME THEME users, to also hide the first thumbnail in the gallery, I directly edited the following file in my child theme folder: \flatsome-child\woocommerce\single-product\product-gallery-thumbnails.php
Maybe there's some similar file for the default Woocomerce gallery or for other themes:
// show first thumbnail only if meta box is NOT checked
<?php if( !rwmb_meta( 'meta_box_hide_first_image' )) : ?>
<div class="col is-nav-selected first">
<a>
<?php
$image_id = get_post_thumbnail_id($post->ID);
$image = wp_get_attachment_image_src( $image_id, apply_filters( 'woocommerce_gallery_thumbnail_size', 'woocommerce_'.$image_size ) );
$image_alt = get_post_meta( $image_id, '_wp_attachment_image_alt', true );
$image = '<img src="'.$image[0].'" alt="'.$image_alt.'" width="'.$gallery_thumbnail['width'].'" height="'.$gallery_thumbnail['height'].'" class="attachment-woocommerce_thumbnail" />';
echo $image;
?>
</a>
</div>
<?php endif; ?>
I can confirm that this is working live on my site right now.

Related

Hiding empty values and Linking values

I am using a WordPress site and wanted to integrate photo captions and photo credit line under the fatured image. I found a great code that adds a Photographer credit and URL field to the media upload page. However, upon displaying it in the page, I want to further customize it.
Currently, when i upload a photo, i can add a photographer name, and a photographer (or source) URL. The URL automatically links to the name if filled in. However, what I want to do is add a text and icon before the photographer name to say "(icon) Image Credit / "
I was able to add it using css, however, when there is no photographer name, it still shows the Image Credit text and icon but no name. How can I hide that when there is no value in the photographer name field?
also, if i enter a photographer name, but no URL, it links the name to an empty URL. How can i make it so that it does not link the name if the URL field is empty?
Here is the code i am working with:
function be_attachment_field_credit( $form_fields, $post ) {
$form_fields['be-photographer-name'] = array(
'label' => 'Photographer Name',
'input' => 'text',
'value' => get_post_meta( $post->ID, 'be_photographer_name', true ),
'helps' => 'If provided, photo credit will be displayed',
);
$form_fields['be-photographer-url'] = array(
'label' => 'Photographer URL',
'input' => 'text',
'value' => get_post_meta( $post->ID, 'be_photographer_url', true ),
'helps' => 'Add Photographer URL',
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'be_attachment_field_credit', 10, 2 );
/**
* Save values of Photographer Name and URL in media uploader
*
* #param $post array, the post data for database
* #param $attachment array, attachment fields from $_POST form
* #return $post array, modified post data
*/
function be_attachment_field_credit_save( $post, $attachment ) {
if( isset( $attachment['be-photographer-name'] ) )
update_post_meta( $post['ID'], 'be_photographer_name', $attachment['be-photographer-name'] );
if( isset( $attachment['be-photographer-url'] ) )
update_post_meta( $post['ID'], 'be_photographer_url', esc_url( $attachment['be-photographer-url'] ) );
return $post;
}
add_filter( 'attachment_fields_to_save', 'be_attachment_field_credit_save', 10, 2 );
Then in my single.php file I added the following code to display the photo credit.
<div id="tgg_credit_line" class="tgg-photo-credit" align="right">
<?php echo "📷 Image Credit / " ?><?php echo get_post_meta(get_post_thumbnail_id(), 'be_photographer_name', true); ?>
</div>
You can first check to see if there is a photographer name set, and if not, don't add any of the credit code. You can also check whether there is a url and then only add the link tag when necessary. This code should be used in place of what you have in the single templates.
<?php
$photographer_name = get_post_meta(get_post_thumbnail_id(), 'be_photographer_name', true);
$photographer_url = get_post_meta(get_post_thumbnail_id(), 'be_photographer_url', true);
if ( $photographer_name ) : ?>
<div id="tgg_credit_line" class="tgg-photo-credit" align="right">
📷 Image Credit /
<?php if ( $photographer_url ) : ?>
<a href="<?php echo $photographer_url ?>">
<?php endif; ?>
<?php echo $photographer_name ?>
<?php if ( $photographer_url ) : ?>
</a>
<?php endif; ?>
</div>
<?php endif; ?>

Display Thumbnails Description with Multiple Post Thumbnails

I've added multiple featured images to my wordpress site using the multiple post thumbnail plugin. I'm trying to display them all underneath the content with their descriptions. I can do it for the main featured image no problem. I can display the rest of the featured images no problem, but whenever I try to add description by it's the page description not the image description.
This is how I added the main image and description.
<?php the_post_thumbnail( 'product-thumbnail' );
echo get_post(get_post_thumbnail_id())->post_content; ?>
The remaining images are added as such:
<?php MultiPostThumbnails::the_post_thumbnail(get_post_type(), 'secondary-
image', NULL, 'product-thumbnail');
?>
And so forth (third, fourth)..
Can somebody help with how to add the descriptions for the rest?
To display your post thumbnail with its caption, simply paste the following code inside the loop:
<?php the_post_thumbnail();
echo get_post(get_post_thumbnail_id())->post_excerpt; ?>
You can also display entire image description by adding this code inside the post loop:
<?php the_post_thumbnail();
echo get_post(get_post_thumbnail_id())->post_content; ?>
the above codes for single images if you use multiple images use this code below
<?php
$the_post_images = get_children( array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type'=> 'image'
) );
foreach ($the_post_images as $the_post_image) {
// SHOW FEATURED IMAGE TITLES
echo get_the_title( $the_post_image->ID );
//SHOW IMAGE DESCRIPTION OR CAPTIONS
echo apply_filters( 'get_the_excerpt', $the_post_image->post_excerpt );
}
?>
To get image, its caption in multiple post thumbnails,
`
echo $secondimgPath = MultiPostThumbnails::get_post_thumbnail_url( get_post_type(), 'second-featured-image', NULL);
echo $secondimgIdAttachment = abcd_get_attachment_id_by_url($secondimgPath);
$size = array( 854,395, 'bfi_thumb' => true, 'quality' => 100);
echo $secondLargeImage[0] = wp_get_attachment_image( $secondimgIdAttachment,$size );
echo get_post( $secondimgIdAttachment )->post_excerpt;
endif; ?>`
In functions.php, use the following -
function abcd_get_attachment_id_by_url( $url ) {
// Split the $url into two parts with the wp-content directory as the separator
$parsed_url = explode( parse_url( WP_CONTENT_URL, PHP_URL_PATH ), $url );
// Get the host of the current site and the host of the $url, ignoring www
$this_host = str_ireplace( 'www.', '', parse_url( home_url(), PHP_URL_HOST ) );
$file_host = str_ireplace( 'www.', '', parse_url( $url, PHP_URL_HOST ) );
// Return nothing if there aren't any $url parts or if the current host and $url host do not match
if ( ! isset( $parsed_url[1] ) || empty( $parsed_url[1] ) || ( $this_host != $file_host ) ) {
return;
}
// Now we're going to quickly search the DB for any attachment GUID with a partial path match
// Example: /uploads/2013/05/test-image.jpg
global $wpdb;
$attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}posts WHERE guid RLIKE %s;", $parsed_url[1] ) );
// Returns null if no attachment is found
return $attachment[0];
}

Warning: Cannot modify header information - headers already sent by in wordpress

unable to add contents in pages like about us ,courses,contact us..while adding the content error is displaying
Warning: Cannot modify header information - headers already sent by (output started at /home/phptraining/public_html/wp-content/themes/health-center-lite/functions.php:95) in /home/phptraining/public_html/wp-admin/post.php on line 235
and
Warning: Cannot modify header information - headers already sent by (output started at /home/phptraining/public_html/wp-content/themes/health-center-lite/functions.php:95) in /home/phptraining/public_html/wp-includes/pluggable.php on line 1196
functions.php
<?php /**Includes reqired resources here**/
define('WEBRITI_TEMPLATE_DIR_URI',get_template_directory_uri());
define('WEBRITI_TEMPLATE_DIR',get_template_directory());
define('WEBRITI_THEME_FUNCTIONS_PATH',WEBRITI_TEMPLATE_DIR.'/functions');
define('WEBRITI_THEME_OPTIONS_PATH',WEBRITI_TEMPLATE_DIR_URI.'/functions/theme_options');
require( WEBRITI_THEME_FUNCTIONS_PATH . '/menu/default_menu_walker.php' ); // for Default Menus
require( WEBRITI_THEME_FUNCTIONS_PATH . '/menu/webriti_nav_walker.php' ); // for Custom Menus
require( WEBRITI_THEME_FUNCTIONS_PATH . '/commentbox/comment-function.php' ); //for comments
require( WEBRITI_THEME_FUNCTIONS_PATH . '/widget/custom-sidebar.php' ); //for widget register
//content width
if ( ! isset( $content_width ) ) $content_width = 900;
//wp title tag starts here
function hc_head( $title, $sep )
{ global $paged, $page;
if ( is_feed() )
return $title;
// Add the site name.
$title .= get_bloginfo( 'name' );
// Add the site description for the home/front page.
$site_description = get_bloginfo( 'description' );
if ( $site_description && ( is_home() || is_front_page() ) )
$title = "$title $sep $site_description";
// Add a page number if necessary.
if ( $paged >= 2 || $page >= 2 )
$title = "$title $sep " . sprintf( _e( 'Page', 'helth' ), max( $paged, $page ) );
return $title;
}
add_filter( 'wp_title', 'hc_head', 10,2 );
add_action( 'after_setup_theme', 'hc_setup' );
function hc_setup()
{ // Load text domain for translation-ready
load_theme_textdomain( 'health', WEBRITI_THEME_FUNCTIONS_PATH . '/lang' );
add_theme_support( 'post-thumbnails' ); //supports featured image
// This theme uses wp_nav_menu() in one location.
register_nav_menu( 'primary', __( 'Primary Menu', 'health' ) );
// theme support
$args = array('default-color' => '000000',);
add_theme_support( 'custom-background', $args );
add_theme_support( 'automatic-feed-links');
require_once('theme_setup_data.php');
require( WEBRITI_THEME_FUNCTIONS_PATH . '/theme_options/option_pannel.php' ); // for Custom Menus
// setup admin pannel defual data for index page
$health_center_lite_theme=theme_data_setup();
function hc_custom_excerpt_length( $length ) { return 50; }
add_filter( 'excerpt_length', 'hc_custom_excerpt_length', 999 );
function hc_new_excerpt_more( $more ) { return '';}
add_filter('excerpt_more', 'hc_new_excerpt_more');
$current_theme_options = get_option('hc_lite_options'); // get existing option data
if($current_theme_options)
{ $hc_lite_theme_options = array_merge($health_center_lite_theme, $current_theme_options);
update_option('hc_lite_options',$hc_lite_theme_options);
}
else
{ add_option('hc_lite_options',$health_center_lite_theme); }
}
/******** health center js and cs *********/
function hc_scripts()
{ // Theme Css
wp_enqueue_style('health-responsive', WEBRITI_TEMPLATE_DIR_URI . '/css/media-responsive.css');
wp_enqueue_style('health-font', WEBRITI_TEMPLATE_DIR_URI . '/css/font/font.css');
wp_enqueue_style('health-bootstrap', WEBRITI_TEMPLATE_DIR_URI . '/css/bootstrap.css');
wp_enqueue_style('health-font-awesome', WEBRITI_TEMPLATE_DIR_URI . '/css/font-awesome-4.0.3/css/font-awesome.min.css');
wp_enqueue_script('health-menu', WEBRITI_TEMPLATE_DIR_URI .'/js/menu/menu.js',array('jquery'));
wp_enqueue_script('health-bootstrap_min', WEBRITI_TEMPLATE_DIR_URI .'/js/bootstrap.min.js');
}
add_action('wp_enqueue_scripts', 'hc_scripts');
if ( is_singular() ){ wp_enqueue_script( "comment-reply" ); }
// Read more tag to formatting in blog page
function hc_content_more($more)
{ global $post;
return ' Read More<i class='fa fa-long-arrow-right'></i>";
}
add_filter( 'the_content_more_link', 'hc_content_more' );
?>
<?php
/**
* Register Widget Area.
*
*/
function wpgyan_widgets_init() {
register_sidebar( array(
'name' => 'Header Sidebar',
'id' => 'header_sidebar',
'before_widget' => '<div>',
'after_widget' => '</div>',
'before_title' => '<h2 class="rounded">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'wpgyan_widgets_init' );
?>
This has nothing to do with functions.php sending headers. Rather, it has to do with output having started (in the functions file) before headers are sent (by other WordPress scripts). What you'll see, if you look on line 95, is the following:
?>
<?php
That blank line between the closing and opening PHP tags is the cause of the error. Instead, you should get rid of both of those tags, so that your code becomes:
add_filter( 'the_content_more_link', 'hc_content_more' );
/**
* Register Widget Area.
*
*/
function wpgyan_widgets_init() {
While you're at it, also delete the last line of your functions.php file (the closing ?> PHP tag). It's unnecessary here.
This error is not specific to wordpress. This is a standard error of PHP. This problem is occurring because you are trying to modify headers after an output is generated in that page like php echo or some html is rendered.
I hope this helps you.

Custom Post Type isn't Appearing

I am relatively new to WordPress development, and I am attempting to build a site-specific plugin that gives me the ability to have a photo album gallery.
A Little Background
Each image will be treated as an attachment (thus getting it’s own single page). I will use the built-in featured thumbnails for album cover photo (Source: http://www.wpbeginner.com/wp-tutorials/how-to-create-a-photo-album-gallery-in-wordpress-without-a-plugin/comment-page-1/#comment-182006)
I essentially have four new files, algallery.php, style.css in my plugin folder and two template folders under templates of a child theme of Roots, archive-albums.php, and single-albums.php.
My problem so far is that when I have implemented get_template_part('templates/archive', 'albums'), I have my "grid" and CSS rendered, but WordPress isn't finding my album posts I've created, and these posts were created with a custom post type. To give you an idea of the approach:
<li class="album-grid">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail('album-grid'); ?>
</a>
</li>
<?php if ( $post->post_type == 'albums' && $post->post_status == 'publish' ) {
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$title = wp_get_attachment_link( $attachment->ID, 'album-grid', true );
echo '<li class="' . $class . ' album-grid">' . $title . '</li>';
}
}
}
?>
I have WP_DEBUG on as well, and I have yet to find the issue. What may be the problem?
What if you add a global $post; at the top of your code ?

How can I get an automatic thumbnail from the first image in a Wordpress post?

I'm creating a Wordpress theme and I'd like to grab the first image in a post as a thumbnail to use in the Facebook's OG meta tag.
I tried using the function get_the_post_thumbnail() but it generates an html img element. Also I'd like to take the first image in the post, without the need of adding a featured image when creating the post.
This should be simple because there are already all thumbnails generated for every post, I'm just not getting it right.
Here I made some function for you that you can hook to add/edit attachment event.
function set_first_as_featured($attachment_ID){
$post_ID = get_post($attachment_ID)->post_parent;
if(!has_post_thumbnail($post_ID)){
set_post_thumbnail($post_ID, $attachment_ID);
}
}
add_action('add_attachment', 'set_first_as_featured');
add_action('edit_attachment', 'set_first_as_featured');
There is a lot of space for improvement, but this one works like a charm too. On every upload / edit attachment, function checks if the post already has featured image. If it has not, image in question is set as featured. Every next picture will be ignored (since post already has featured image).
Maybe someone finds it helpful (you found solution in the middle of my coding, so... :) )
I found this solution:
$size = 'thumbnail'; // whatever size you want
if ( has_post_thumbnail() ) {
the_post_thumbnail( $size );
} else {
$attachments = get_children( array(
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'numberposts' => 1)
);
foreach ( $attachments as $thumb_id => $attachment ) {
echo wp_get_attachment_image($thumb_id, $size);
}
}
I found a solution:
wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail' )[0];
It works fine.
Put this code in your theme's functions.php:
// make the first image of WordPress post as featured image
function first_image_as_featured() {
global $post, $posts;
$first_img_featured = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img_featured = $matches [1] [0];
if(empty($first_img_featured)){ //Defines a default image
$first_img_featured = "/images/default.jpg";
}
return $first_img_featured;
}
Then add the below code inside WordPress loop:
<?php
if (has_post_thumbnail()) { ?>
<?php the_post_thumbnail(); ?>
<?php }
else { ?>
<img src="<?php echo first_image_as_featured(); ?>" />
<?php
}
?>
If the featured image not set, it will automatically take the first image as featured image.
Source: Get The First Image Of WordPress Post As Featured Image
I have tried the solutions above withou success. So, I build a new and easy solution:
function set_first_as_featured($post_id){
$medias = get_attached_media( 'image', $post_id );
if(!has_post_thumbnail($post_id)) {
foreach ($medias as $media) {
set_post_thumbnail($post_id, $media->ID);
break;
}
}
}
add_action('save_post', 'set_first_as_featured');
When you save a post, this code will check if it has any thumbnail. If not, so it will set the first image attached to this post as thumbnail.

Categories