Showing image caption only if caption exists - Wordpress - php

I found a really helpful discussion here that outlines how to display the image caption, alt, title, etc. I've tested this function, and it works well, but for the images that don't have captions, the div for the caption still displays. How would I go about making this function display nothing, if there's no caption available?
function the_post_thumbnail_caption() {
global $post;
$thumb_id = get_post_thumbnail_id($post->id);
$args = array(
'post_type' => 'attachment',
'post_status' => null,
'post_parent' => $post->ID,
'include' => $thumb_id
);
$thumbnail_image = get_posts($args);
if ($thumbnail_image && isset($thumbnail_image[0])) {
//show thumbnail title
echo $thumbnail_image[0]->post_title;
//Uncomment to show the thumbnail caption
//echo $thumbnail_image[0]->post_excerpt;
//Uncomment to show the thumbnail description
//echo $thumbnail_image[0]->post_content;
//Uncomment to show the thumbnail alt field
//$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
//if(count($alt)) echo $alt;
}
}

if ($thumbnail_image[0]->post_excerpt != '')
{
echo $thumbnail_image[0]->post_excerpt;
}

Related

Checking for alt text on images added to Wordpress content

I want to require that Wordpress editors must add alt text to images.
The site uses the classic editor and images are added into the content editor. I have chosen to do this in php by checking if images have alt text when saving the post. If all images do not have alt tags, then prevent the post from being published and show a message in the admin.
Here is the code I have. My problem is that the code to return the alt text always returns an empty string. Can someone help me pin down what I'm doing wrong? Also, not averse to a different approach altogether...
add_action('save_post', 'check_content_for_images');
function check_content_for_images($post_id) {
$attachments = get_children( array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'numberposts' => -1, // show all -1
'post_status' => 'inherit',
'post_mime_type' => 'image',
) );
// loop through images and check that it has an alt attribute
$counter = 0;
foreach ($attachments as $attachment_id => $attachment) {
// $img = wp_get_attachment_image($attachment_id, 'full');
$alt_text = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
if(empty($alt_text)) {
$counter++;
}
}
if ( count($attachments) > $counter) {
// set a transient to show the users an admin message
set_transient( "post_not_ok", "not_ok" );
// // unhook this function so it doesn't loop infinitely
remove_action('save_post', 'check_content_for_images');
// // update the post set it to draft
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
// // re-hook this function
add_action('save_post', 'check_content_for_images');
} else {
delete_transient( "post_not_ok" );
}
}
/**
* Do not show post published message
*/
add_filter( 'post_updated_messages', 'abc_remove_all_messages' );
function abc_remove_all_messages( $messages ) {
if ( get_option( 'abc_post_error' ) ) {
return array();
} else {
return $messages;
}
}
// add a admin message to inform the user the post has been saved as draft.
function showAdminMessages()
{
// check if the transient is set, and display the error message
if ( get_transient( "post_not_ok" ) == "not_ok" ) {
// Shows as an error message. You could add a link to the right page if you wanted.
showMessage("One or more of the images included in this post is missing ALT text. Please ensure all images have ALT text", true);
// delete the transient to make sure it gets shown only once.
delete_transient( "post_not_ok" );
}
}
add_action('admin_notices', 'showAdminMessages');
// function to display the errormessage
function showMessage($message, $errormsg = false)
{
if ($errormsg) {
echo '<div id="message" class="error">';
}
else {
echo '<div id="message" class="updated fade">';
}
echo "<p><strong>$message</strong></p></div>";
}

How can I display the featured icon on frontend?

Hello I applied the code I found here.
But I can't figure out how can I call this image on frontend.
I tried this so far:
$args = array('post_type' => 'katastima');
$the_query = new WP_Query($args);
while ( $the_query->have_posts() ) : $the_query->next_post();
$id= $the_query->post->ID;
$location = get_post_meta($id, 'listingimagediv', true);
echo $location;
endwhile;
but I guess this is not the correct way to get the image link from the custom metabox.
Any suggestions?
Thanks in advance.
You get the photo ID from get_post_meta
So the next step is to get the url of the image, see here
$size = 'full';
$icon = null;
$attr = array( "class" => "img-responsive" );
echo wp_get_attachment_image( $location, $size, $icon, $attr );

rewrite function to not use echo php for use with short_code

I am having a bit of trouble getting my shortcode to place my html of a function in the correct place on wordpress. After some research I have found that when using shortcodes you cannot have echo used in the function. I have been doing my best to write the function without any echo's but cant seem to get it to work. I have little actual experience with PHP as a language and am giving this my best shot.
The top code block is the functioning code with echo used throughout, and the second is the rewritten code without any echo but is not functioning. Anyone have an idea where my rewrite is going wrong? Or possibly have a better work around then rewriting the function?
First:
function na_get_gallery_image_urls( $post_id ) {
$post = get_post($post_id);
// Make sure the post has a gallery in it
if( ! has_shortcode( $post->post_content, 'gallery' ) )
return;
//initiate counter to be able to keep track of images
$count_img = 0;
// Retrieve all galleries of this post
$gallery = get_post_gallery_images( $post );
// Loop through each image in first gallery
foreach( $gallery as $image ) {
// Below here are the main containers and first large image; stuff we will only want to output one time.
if($count_img == 0) { ?>
<!-- Whole Gallery container (inludes thumbnails) -->
<div id="instant-gallery">
<!-- Main Display Area -->
<div id="ig-main">
<!-- Set the parameters for the image we are about to display. -->
<?php
$default_attr = "ig-hero";
?>
<!-- Display the first image attachment as the large image in the main gallery area -->
<img src="<?php print $image; ?>" id="<?php print $default_attr; ?>">
<a href="<?php print $image; ?>" download>Download</a>
<!-- Close the main display area -->
</div>
<!-- Open the Thumbnail navigation -->
<ul id="ig-thumbs">
<!-- End the block of stuff that we only do for the first image -->
<?php } ?>
<!-- Now, for each of the thumbnail images, label the LI with an ID of the appropriate thumbnail number -->
<li id="ig-thumb-<?php print $count_img+1; ?>">
<?php if ($count_img==0) {
// If this is the first thumbnail, add a class of 'selected' to it so it will be highlighted
$thumb_attr = "thumb selected";
} else {
// For all other thumbnails, just add the basic class of 'thumb'
$thumb_attr = "thumb";
} ?>
<!-- Output a thumbnail-sized version of the image that has the attributes defined above -->
<img src="<?php print $image; ?>" class="<?php print $thumb_attr; ?>">
</li>
<!-- Increment the counter so we can keep track of which thumbnail we are on -->
<?php $count_img = $count_img + 1; } ?>
<!-- Close the thumbnail navigation list -->
</ul>
<!-- Close the entire Gallery -->
</div>
<?php
}
function instant_gallery() {
global $post;
$args = array(
'post_parent' => '$post->ID', // For the current post
'post_type' => 'attachment', // Get all post attachments
'post_mime_type' => 'image', // Only grab images
'order' => 'ASC', // List in ascending order
'orderby' => 'menu_order', // List them in their menu order
'numberposts' => -1, // Show all attachments
'post_status' => null, // For any post status
);
// Retrieve the items that match our query; in this case, images attached to the current post.
na_get_gallery_image_urls($args[0]);
}
// Create the Shortcode
add_shortcode('instant_gallery', 'instant_gallery');
?>
last:
function na_get_gallery_image_urls( $post_id ) {
$post = get_post($post_id);
// Make sure the post has a gallery in it
if( ! has_shortcode( $post->post_content, 'gallery' ) )
return;
// initiate counter to be able to keep track of images
$count_img = 0;
// Retrieve all galleries of this post
$gallery = get_post_gallery_images( $post );
// Loop through each image in first gallery
foreach( $gallery as $image ) {
// Below here are the main containers and first large image; stuff we will only want to output one time.
if($count_img == 0) {
//<!-- Whole Gallery container (inludes thumbnails) -->
$hero_img = '<div id="instant-gallery">';
//<!-- Main Display Area -->
$hero_img .= '<div id="ig-main">';
//<!-- Set the parameters for the image we are about to display. -->
$default_attr = "ig-hero";
//<!-- Display the first image attachment as the large image in the main gallery area -->
$hero_img .= '<img src="' . $image . '" id="' . $default_attr . '">';
$hero_img .= '<a href="' . $image . '" download>Download</a>';
//close main display area
$hero_img .= '</div>';
//<!-- Open the Thumbnail navigation -->
$hero_img .= '<ul id="ig-thumbs">';
//<!-- End the block of stuff that we only do for the first image -->
}
//<!-- Now, for each of the thumbnail images, label the LI with an ID of the appropriate thumbnail number -->
$thumbs = '<li id="ig-thumb-' . ($count_img + 1) . '">';
if ($count_img==0) {
// If this is the first thumbnail, add a class of 'selected' to it so it will be highlighted
$thumb_attr = "thumb selected";
} else {
// For all other thumbnails, just add the basic class of 'thumb'
$thumb_attr = "thumb";
}
//<!-- Output a thumbnail-sized version of the image that has the attributes defined above -->
$thumbs .= '<img src="' . $image . '" class="' . $thumb_attr . '">' . '</li>';
//<!-- Increment the counter so we can keep track of which thumbnail we are on -->
$count_img = $count_img + 1;
}
//<!-- Close the thumbnail navigation list -->
$fin = '</ul>';
// <!-- Close the entire Gallery -->
$fin .= '</div>';
$content = "$hero_img" . "$thumbs" . "$fin";
return $content;
}
function instant_gallery() {
global $post;
$args = array(
'post_parent' => '$post->ID', // For the current post
'post_type' => 'attachment', // Get all post attachments
'post_mime_type' => 'image', // Only grab images
'order' => 'ASC', // List in ascending order
'orderby' => 'menu_order', // List them in their menu order
'numberposts' => -1, // Show all attachments
'post_status' => null, // For any post status
);
// Retrieve the items that match our query; in this case, images attached to the current post.
na_get_gallery_image_urls($post->ID);
}
// Create the Shortcode
add_shortcode('instant_gallery', 'instant_gallery');
?>
Hi Try below code with changing your parameters it will works.
function testgallery_shortcode( $atts , $content = null ) {
extract( shortcode_atts(
array(
'title' =>'TEST GALLERY',
'items' =>3,
), $atts )
);
$args = array(
'post_type' => 'testgallery',
'posts_per_page' => $items,
'post_status' => 'publish',
);
$test_gallery = new WP_Query( $args );
$html = '';
global $post;
if ( $test_gallery->have_posts() ) :while ( $test_gallery->have_posts() ) : $test_gallery->the_post();
$html.='<div class="col-sm-4 col-xs-12">';
$html.='<figure class="post">';
$html.='<div class="image-wrap">';
$html.='<a class="zoomtoplay" alt="gallery_image" href="'. esc_url( get_permalink() ).'"></a>';
if (has_post_thumbnail() ) {
$imgarray = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID),'full');
$imgURL = $imgarray[0];
$html.='<img src="'.$imgURL.'" class="img-responsive"/>';
}
$html.='</div><h3>'.get_the_title().'</h3>';
$html.='</figure>';
$html.='</div>';
endwhile;
endif;
wp_reset_query();
return $html;
}
add_shortcode( 'testgallery', 'testgallery_shortcode' );
-- Now you can use a [testgallery] shortcode in your post and page.
This is a standard way of creating shortcode.
Still if needed than For more details you can visit this link - https://www.sitepoint.com/custom-shortcodes-for-wordpress/

Wordpress: Moving inline images to Featured Galleries

Here's my situation:
I'm redesigning an existing Wordpress site.
The new design separates all images from the actual post content and puts it in a Featured Gallery.
Currently, each post has your typical inline images in the post content.
Is this even remotely possible to extract all inline images from the post content, and create Featured Galleries with those images for each post?
In the past I've done something like the below to grab the first image in the post content, and set it as the standard featured image, but nothing like what I have to do with this dilemma.
function wpforce_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
}
}
} //end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');
Basically the method I used was to create a one time script that I ran to move all inline images from the post to the Featured Gallery, like this:
// Loop over every post
while ( have_posts() ) : the_post();
// Get the images attached to the post.
$imageids = array();
$images = get_attached_media( 'image', $post->ID );
foreach ($images as $image) {
$imageids[] = $image->ID;
}
$comma_separated = implode(",", $imageids);
// Save them to the Featured Gallery (Got this info by digging into the Featured Gallery plugin's source code)
if ( $post->post_type == 'revision' ) {return;}
if ( get_post_meta( $post->ID, 'fg_perm_metadata', FALSE ) ) {
update_post_meta( $post->ID, 'fg_perm_metadata', $comma_separated );
} else {
add_post_meta( $post->ID, 'fg_perm_metadata', $comma_separated );
}
if ( !$comma_separated ) delete_post_meta( $post->ID, 'fg_perm_metadata' );
endwhile;
// Reset Query
wp_reset_query();
Then, I created a function that removes all images in the post content, which I placed in functions.php:
function remove_images( $content )
{
$content =
preg_replace(
array('{<a(.*?)(wp-att|wp-content\/uploads)[^>]*><img}',
'{ wp-image-[0-9]*" /></a>}'),
array('<img','" />'),
$content
);
$content = preg_replace('/<img(.*)>/i','', $content, 1);
return $content;
}
add_filter( 'the_content', 'remove_images' );
First preg_replace removes the link around the images. Second removes the image.
the problem is if i read you correctly is that all the images are located as urls in the post content?
You can parse them:
$content = get_the_content();
$html = new DOMDocument;
$html->loadHTML($content);
//get the images
$images = $html->getElementsByTagName('img');
foreach($images as $image=>$key {
$imageurls[]=$key->attributes->getNamedItem("src")->value;//play with this cant remember how it returns object.
}
$content= preg_replace('/<img(.*)>/i','',$content,1);
echo $content;
// you also have a array of images to use.

Wordpress get the first attached image on the post

Today I've been trying to display the most popular post in wordpress using the following code:
http://pastebin.com/TjJTiiTZ
It works great however it's not allowing me to grab the first attached image on the post. I need to do it that way in order to get the image from any of the several custom fields holding the images.
I tried to use the following code (which actually works on another customization) to get the first attached image on the post but I have not been able to make it work.
$p = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => 1,
'order' => 'ASC',
'orderby' => 'menu_order ID',
'post_status' => null,
'post_parent' => $post->ID
);
$thumb = get_posts($p);
if ($thumb) {
$imgsrc = wp_get_attachment_image_src($thumb[0]->ID, 'thumbnail');
$img = $imgsrc[0];
}
Is there any way in which this can be accomplish??
You can use this code to get posts first attachment image:
$catposts = get_posts('category='.$category_id."&order=DESC&numberposts=".$NUMBEROFPOSTS);
function catch_that_image($_catposts)
{
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $_catposts->post_content, $matches);
$first_img = $matches[1][0];
return $first_img;
}
$j=0;
foreach ($catposts as $item) :
$get_contents = $item->post_content;
$regex_pattern = "/<a href=\"(.*)\">(.*)<\/a>/";
$output = preg_match_all($regex_pattern,$item->post_content, $matches);
echo '<img src="'.catch_that_image($catposts[$j]).'" alt="" border="0px" />';
$j++;
endforeach;
where $category_id is specific category id . suppose if you have a category id = 26 then all 26 category posts display in foreach loop.
on that related posts first image display which you enter in posts.
Thank you.

Categories