Is there a way to display the image caption where ever available when displaying the_post_thumbnail() image in WordPress on the posts in the primary loop.
Thanks! Appreciate all the help.
Here is an easier and shorter code :
<?php the_post_thumbnail();
echo get_post(get_post_thumbnail_id())->post_excerpt; ?>
As of WordPress 4.6, the function the_post_thumbnail_caption() has been added to core (/wp-includes/post-thumbnail-template.php).
Using the code posted here will cause the error:
Fatal error: Cannot redeclare the_post_thumbnail_caption()
I figured it out:
/************************************************************\
* Fetch The Post Thumbnail Caption
\************************************************************/
function the_post_thumbnail_caption() {
global $post;
$thumbnail_id = get_post_thumbnail_id($post->ID);
$thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));
if ($thumbnail_image && isset($thumbnail_image[0])) {
echo $thumbnail_image[0]->post_excerpt;
}
}
if(!function_exists('get_post_thumbnail_caption')) {
function get_post_thumbnail_caption($post_id = null) {
$post_id = ( null === $post_id ) ? get_the_ID() : $post_id;
$thumbnail_id = get_post_thumbnail_id($post_id);
if ($thumbnail = get_post($thumbnail_id))
return $thumbnail->post_excerpt;
return '';
}
}
if(!function_exists('the_post_thumbnail_caption')) {
function the_post_thumbnail_caption($post_id = null) {
echo get_post_thumbnail_caption($post_id);
}
}
if(has_post_thumbnail()) {
the_post_thumbnail();
the_post_thumbnail_caption();
$caption = get_post_thumbnail_caption(123);
if('' == $caption)
echo '<div class="caption">'.$caption.'</div>';
}
Related
newbie here. I'm using the following code to extract the secondary image source of my wordpress posts, but I think I could shorten it someway...
Here is the code I'm currently using inside img src=""
<?php $images = get_attached_media('image'); $featured_image_id = get_post_thumbnail_id(); if ( has_post_thumbnail() ) { unset($images[ $featured_image_id ] ); } $harukunt = wp_get_attachment_image_src( key($images),'large'); echo '' . $harukunt[0] . ''; ;?>
Maybe I could simplify this by defining some values in the header.php file, so then I can call the image in a shorter way in the posts?
<?php
$images = get_attached_media('image');
$featured_image_id = get_post_thumbnail_id();
if ( has_post_thumbnail()
)
{ unset($images[ $featured_image_id ] );
}
$harukunt = wp_get_attachment_image_src( key($images),'large');
echo '' . $harukunt[0] . '';
;
?>
And then call the image on posts by simply using img src="<?php harukunt("$post->ID"); ?>" or something. But it isnt working this way, due to my poor knownledge.
Can anybody please help me?
You can create a function and add it to your functions.php file like this:
function get_secondary_img($post_id, $print = true ){
if(has_post_thumbnail($post_id)) {
$attachments = get_attached_media('image',$post_id);
if(count($attachments) < 2){
$attachment_id = get_post_thumbnail_id($post_id);
} else {
foreach($attachments as $key => $attachment){
if($key !== get_post_thumbnail_id($post_id)){
$attachment_id = $key;
break;
}
}
}
if($attachment_id){
$attachment = wp_get_attachment_image_src($attachment_id,'large');
$src = $attachment[0];
$width = $attachment[1];
$height = $attachment[2];
$alt = get_post_meta($attachment_id,'_wp_attachment_image_alt',true);
if($print == true){
echo '<img width="'.$width.'" height="'.$height.'" src="'.$src.'" alt="'.$alt.'" />';
} else {
return $src;
}
}
}
}
Then if you want to output the html for the image you can just do
<?php echo get_secondary_img( $post_id ); ?>
Or if you want to just return the src attribute, you can just do
$yourvariable = get_secondary_img( $post_id, false );
I'm using a wp theme which comes with an ajax search feature to get live suggestions. However the suggestion element displays the post type (under the resulted title) such as "Portfolio item" and I would like to replace it with the post (portfolio item's) category. Any solution? Thanks in advance!
$suggestions=array();
global $post;
foreach ($posts as $post): setup_postdata($post);
// Initialise suggestion array
$suggestion = array();
$suggestion['label'] = esc_html($post->post_title);
$suggestion['link'] = get_permalink();
$suggestion['image'] = (has_post_thumbnail( $post->ID )) ? get_the_post_thumbnail($post->ID, 'thumbnail', array('title' => '')) : '<i class="icon-salient-pencil"></i>' ;
if(get_post_type($post->ID) == 'post'){
$suggestion['post_type'] = __('Story',NECTAR_THEME_NAME);
} else if(get_post_type($post->ID) == 'page'){
$suggestion['post_type'] = __('Page',NECTAR_THEME_NAME);
} else if(get_post_type($post->ID) == 'portfolio'){
$suggestion['post_type'] = __('Portfolio item',NECTAR_THEME_NAME);
//show custom thumbnail if in use
$custom_thumbnail = get_post_meta($post->ID, '_nectar_portfolio_custom_thumbnail', true);
if(!empty($custom_thumbnail) ){
$attachment_id = pn_get_attachment_id_from_url($custom_thumbnail);
$suggestion['image'] = wp_get_attachment_image($attachment_id,'portfolio-widget');
}
} else if(get_post_type($post->ID) == 'product'){
$suggestion['post_type'] = __('Product',NECTAR_THEME_NAME);
}
I have a plugin that adds a meta box with file upload form, the plugin works perfectly, displays the link of the image in the meta box (View Image), load the file, and once published the post, it views in the theme. (in the example I'm using an image file):
<?php
/* Plugin Name: Custom Meta Upload Template*/
add_action('post_edit_form_tag', 'post_edit_form_tag');
function post_edit_form_tag() {
echo ' enctype="multipart/form-data"';
}
function custom_upload() {
add_meta_box( 'meta_upload', __( 'Upload Image', 'meta_upload_domain' ),'meta_upload_callback', 'post' );}
add_action( 'add_meta_boxes', 'custom_upload' );
function meta_upload_callback( $post ) {
global $post;
$custom = get_post_custom($post->ID);
$download_image01 = get_post_meta($post->ID, '_image01', true);
echo '<p><label for="document_file">Upload document:</label><br />';
echo '<input type="file" name="document_file" id="document_file" /></p>';
echo '</p>';
if(!empty($download_image01) && $download_image01 != '0') {
echo '<p>View Image</p>';
}
}
function meta_upload_save( $post_id ) {
global $post;
if(strtolower($_POST['post_type']) === 'page') {
if(!current_user_can('edit_page', $post_id)) {
return $post_id;
}
}
else {
if(!current_user_can('edit_post', $post_id)) {
return $post_id;
}
}
if(!empty($_FILES['document_file'])) {
$file = $_FILES['document_file'];
$upload = wp_handle_upload($file, array('test_form' => false));
if(!isset($upload['error']) && isset($upload['file'])) {
$title = $file['name'];
$ext = strrchr($title, '.');
$title = ($ext !== false) ? substr($title, 0, -strlen($ext)) : $title;
$attachment = array(
'post_mime_type' => 'image',
'post_title' => addslashes($title),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post->ID
);
$attach_key = '_image01';
$attach_id = wp_insert_attachment($attachment, $upload['file']);
$existing_download = (int) get_post_meta($post->ID, $attach_key, true);
if(is_numeric($existing_download)) {
wp_delete_attachment($existing_download);
}
update_post_meta($post->ID, $attach_key, $attach_id);
}
}
}
add_action( 'save_post', 'meta_upload_save' );
and he called the file in the theme:
<?php
$download_image01 = get_post_meta($post->ID, '_image01', true);
if(!empty($download_image01) && $download_image01 != '0') { ?>
<div class="section-content">
<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />
</div>
<?php }?>
I repeat, the plugin works, but the problem is that I can not place a button or a checkbox that deletes the file when, for example, I want to edit the post, and delete the file, and of course the link "View Image" disappears
Any idea!!
Whenever you want to edit these fields echo the value of the custom fields look like this...
<input type="" value="<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />">
When you edit the post it's get the value and show the uploaded image's to you.
I don't know if that can help, but I use this code to exclude Attachment when I delete a Custom Post:
add_action('before_delete_post', 'delete_all_attached_media');
function delete_all_attached_media($post_id)
{
if (get_post_type($post_id) == "your-custom-post-type") {
$attachments = get_attached_media('', $post_id);
foreach ($attachments as $attachment) {
wp_delete_attachment($attachment->ID, 'true');
}
}
}
This could be a duplicate question, but not one of these similiar questions has touched the get_attached_media part, which is what I need help with.
If I don't have any Featured Image in the post, I want to use the image attached in the content of the post, as a Featured Image.
Here is what I'm trying and failing:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
if(get_post_thumbnail_id() == TRUE) {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
}
else {
$image_url = wp_get_attachment_image_src( get_attached_media('image'), 'backstretch');
}
?>
<header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo $image_url[0]; ?>">
I've realised I need to fetch the url of get_attached_media('image') for it to work. But even with using foreach I've not managed this:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
function get_image($arr) {
$images = get_attached_media('image');
$arr = [];
foreach($images as $image) {
$url = wp_get_attachment_url($image->ID);
$image_url = wp_get_attachment_image_src($url, 'backstretch');
$arr[] = $image_url;
}
return $arr;
}
?>
<header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo get_image($arr[0]); ?>">
My url becomes this:
http://site.loc/wp/2016/01/05/postname/%3Cbr%20/%3E%3Cfont%20size='1'%3E%3Ctable%20class='xdebug-error%20xe-notice'%20dir='ltr'%20border='1'%20cellspacing='0'%20cellpadding='1'%3E%3Ctr%3E%3Cth%20align='left'%20bgcolor='
Which clearly states that it gets image attributes as url. I've googled and played with the code, and I just can't find realize the problem.
I really appreciate your help.
Also if you still find this as a duplicate, I apologize!
I use this function to get all available images from a WordPress post:
function get_post_images( $post = null ) {
if ( $post === null ) {
global $post;
}
/* Get the featured image of the post */
if ( has_post_thumbnail() ) {
$images[] = get_post_thumbnail_id( $post->ID );
}
/* If the post contains galleries, get all images from them */
if( has_shortcode( $post->post_content, 'gallery' ) ) {
$galleries = get_post_galleries( $post, false );
foreach ( $galleries as $gallery ) {
$ids = explode( ',', $gallery['ids'] );
$images = array_merge( $images, $ids );
}
}
/* Get all single images in the post */
preg_match_all("/wp-image-(\d+)/", $post->post_content, $imgs );
foreach ($imgs[1] as $img) {
$images[] = $img;
}
/* get all images attached to the post
* not sure if this is a good idea, there might be images attached
* which were not supposed to be published */
$post_images = get_posts( array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'numberposts' => -1,
'post_mime_type' => 'image',
'exclude' => $images ) );
foreach ( $post_images as $image ) {
$images[] = $image->ID;
}
/* As a fallback, add a predefined default image */
if ( sizeof( $images ) == 0 && $this->default_image != null) {
$images[] = $this->default_image;
}
/* remove duplicated images */
$images = array_unique( $images );
return $images;
}
The function returns an array containing all image IDs related to the given post, if you only need one you can extract that easily:
$images = get_post_images();
echo wp_get_attachment_image( array_shift( $images ) );
Well, I fixed the problem. I tried to use the popular get_that_image plugin, but it didn't fix my problem. At the end of the day I trashed the get_attached_media, and used this function which I found here.
function crisp_catch_that_image() {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
if (!empty($image_url)) {
return $image_url[0];
}
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (empty($matches[1])) {
return '';
}
return $matches[1][0];
return $first_img;
}
If a page is not having featured image, display the featured image of its parent page.
If again that parent is not having featured image, get it from the next higher level and so on till featured image is found or last level is reached.
Is there a solution for this in Wordpress?
You can use a recursive function like this:
function get_featured_recursive($post) {
if (has_post_thumbnail( $post->ID ) ) {
return $post->ID;
} else if (!has_post_thumbnail($post->ID) && $post->post_parent != 0) {
$parent = get_post($post->post_parent);
if (has_post_thumbnail($parent->ID)){
return $parent->ID;
}
} else if(!has_post_thumbnail($parent->ID) && $parent->post_parent != 0){
get_featured_recursive(get_post($parent->post_parent));
}
else if(!has_post_thumbnail($parent->ID) && $parent->post_parent == 0 )
{
return null;
}
}
Then in your template use this to display the featured image:
< ?php $featured_image_post = get_featured_recursive($post);
if ($featured_image_post != null) : $featured_image_src = wp_get_attachment_image_src(get_post_thumbnail_id($featured_image_post), 'single-post-thumbnail'); ?>
Add the below code in your functions.php and modify as per your need:
function get_featured_recursive($post) {
if (has_post_thumbnail( $post->ID ) ) {
return $post->ID;
} else if ($post->post_parent != 0) {
return get_featured_recursive(get_post($post->post_parent));
} else {
return null;
}
}
//In you display page:
div id="featured">
< ?php $featured_image_post = get_featured_recursive($post); if ($featured_image_post != null) : $featured_image_src = wp_get_attachment_image_src(get_post_thumbnail_id($featured_image_post), 'single-post-thumbnail'); ?>
<div id="featured-bg"><img src="<?php echo$featured_image_src[0]; ?>" alt="<?php echo the_post_thumbnail_caption_from_id($featured_image_post); ?>" /> </div> </div> <div id="featured-caption">< ?php echo the_post_thumbnail_caption_from_id($featured_image_post); ?></div></div>