I have the following code in my wordpress theme, single-post page (the page where single posts are displayed).
<article id="post-<?php the_ID(); ?>"<?php post_class('col-md-12'); ?>>
<div class="container">
<header class="entry-header">
<h1 class="entry-title"><?php the_title(); ?></h1>
</header>
<?php
$thumb = get_post_thumbnail_id();
$img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use "large" or "medium" if the images too big)
$image = aq_resize( $img_url, 1200, 720, true ); //resize & crop the image
?>
<?php if($image) : ?>
<img class="img-responsive singlepic" src="<?php echo $image ?>"/>
<?php endif; ?>
<?php if ( $post->post_type == 'data-design' && $post->post_status == 'publish' ) {
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
}
}
?>
<div class="entry-content">
<?php the_content(); ?>
<?php
wp_link_pages( array(
'before' => '<div class="page-links">' . __( 'Pages:', 'web2feel' ),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->
</div>
</article><!-- #post-## -->
It puts the post-title then featured-image as a large image then posts the content, and then the rest.
I want to target the images in the content, and display them the same way as the featured-image is displayed.
*NOTE - changes to the 'if ( $attachments ) { ...' function doesn't change anything (nor does completely removing it) so I am not certain what that part does. the only code that affects the content is when it is called ( '')
Sometimes ago I used to following code to strip off all the images in my content area and then display them separately apart from the contents. This might help you.
In your functions.php file -
function stripe_images_from_content($content){
$images = array();
$subject = $content;
$subject = preg_replace('~<img [^\>]*\ />~', '', $subject);
$subject = preg_replace('~\[caption[^\]]*\][^\]]*\]~', '', $subject);
$image_urls = array();
$match_count = preg_match_all( '/<img.*src=["\']([^"\']*)["\'].*\/>/', $content, $image_urls );
if (is_numeric($match_count) && $match_count > 0) {
if( is_array($image_urls[1]) and count($image_urls[1]) > 0 ){
foreach( $image_urls[1] as $i ){
$featured_image_url = $i;
$image_id = get_attachment_id_from_src( $featured_image_url );
if (! is_numeric($image_id)) {
$match_count = preg_match( '/(.*)-\d+x\d+(\.(jpg|png|gif))/', $featured_image_url, $matches );
if (is_numeric($match_count) && $match_count > 0) {
$base_image_url = $matches[1] . $matches[2];
$images[] = get_attachment_id_from_src( $base_image_url );
}
}
else{
$images[] = $image_id;
}
}
}
}
$data = new stdClass();
$data->images = $images;
$data->content = $subject;
return $data;
}
What this function does is get all the images inserted in the content area of a post and strip them off. Then return the image(s) and the content without image.
in your single.php file-
$content = stripe_images_from_content(get_the_content());
Now you need to do two things. $content->images contains all the images inserted in the post content area. And $content->content holds the raw content images stripped off. First you need to use $content->images wisely where you want to display your images and second replace the the_content() function with echo wpautop($content->content);
Hope this might help you.
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 have set up the header on my WordPress to work wonderfully on the home page. The header is supposed to change to the newest post that I have created and it works.
The problem is that my header does not show up on any pages. I feel that I am missing a bit of code (specifically a conditional statement) that would disable the change and just let pages have the featured image that I set on the dashboard.
The code:
<?php
$recent = get_posts( array('numberposts' => 10) );
$src = false;
if(is_home()){
foreach($recent as $p){
if( has_post_thumbnail( $p->ID ) ){
$src = wp_get_attachment_image_src( get_post_thumbnail_id($p->ID), array( 5600,1000 ), false, '' );
}
$title = get_the_title();
$date = get_the_date();
break;
}
}
?>
<div class="hero-image" style="background-image: url('<?php echo esc_url( $src[0] ) ?>')">
<div id="hero-text" class="thumbnail-text">
<h1><?php echo $title?></h1>
<h2><?php echo $date?></h2>
</div>
</div>
I've tried
if(!is_home()){
result
}
else{
result
}
And tried to put it in the CSS, but it broke.
I was able to solve the issue with the following:
<?php
$recent = get_posts( array('numberposts' => 10) );
$src = false;
if(is_home()){
foreach($recent as $p){
if( has_post_thumbnail( $p->ID ) ){
$src = wp_get_attachment_image_src(
get_post_thumbnail_id($p->ID), array( 5600,1000 ), false, '' );
}
$title = get_the_title();
$date = get_the_date();
break;
}
} else if(!is_home()) {
if( has_post_thumbnail( $p->ID ) ){
$src = wp_get_attachment_image_src(
get_post_thumbnail_id($p->ID), array( 5600,1000 ), false, '' );
$title = get_the_title();
$date = get_the_date();
}
}
?>
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;
}
After scratching my head for almost 2 hours, I am unable to resolve the puzzle. Anyone who could help me , I will be highly thankful to him.
I have created a custom post type 'Properties' in wordpress. I am trying the following code to list the properties in a page. All of it is displaying fine except Images.
<?php
$conarg = array (
'post_type' => 'properties',
'order_by' => 'menu_order',
'order' => 'ASC'
);
$condo_query = new WP_Query( $conarg );
if ( $condo_query->have_posts() ) { ?>
<?php
while ( $condo_query->have_posts() ) {
$condo_query->the_post();
?>
<?php
$condo_images_max = 5;
$condo_items = array();
for($i=1; $i <= condo_images_max; $i++) {
//check if image exits
$img_attachment_id = get_field('gallery-image-'.$i);
if(!empty($img_attachment_id)) {
$condo_items[$i] = array(
'image' => wp_get_attachment_image_src($img_attachment_id, 'medium')
);
}
}
$condo_items_keys = array_keys($condo_items);
?>
<div class="box col-md-4 col-xs-12">
<div class="flexslider">
<ul class="slides">
<?php
for($i=0; $i < count($condo_items) ; $i++) {
$image = $condo_items[$condo_items_keys[$i]]['image'];
?>
<li>
<img src="<?php echo $image[0]; ?>" alt="Carousel Image" />
</li>
<?php
}
?>
</ul>
</div>
<?php echo '<h2 class="condo-title">' . get_the_title() . '</h2>';
echo'<ul class="condo-details">';
if(get_field('area_range')) {
echo '<li><span>SQ.FT RANGE:</span> ' . get_field('area_range') . '</li>';
}
if(get_field('room_view')) {
echo '<li><span>ROOM VIEW:</span> ' . get_field('room_view') . '</li>';
}
if(get_field('price_range')) {
echo '<li><span>PRICE RANGE:</span> ' . get_field('price_range') . '</li>';
}
?>
<a class="condo-btn" href="<?php the_permalink(); ?>"><?php _e('VIEW DETAILS'); ?></a>
<?php
echo'</ul></div>';
}
}
else {
echo'Sorry! No Condos are available at the moment!';
}
/* Restore original Post Data */
wp_reset_postdata();
?>
As I mentioned in my comment it's probably worth switching to the PRO version and using a repeater field.
In your question you're overcomplicating this by unnecessarily building an array and then looping through your array using for instead of foreach.
Remove the code to build an array and try this instead of your current output code:
<ul class="slides">
<?php // Set maximum number of images to check.
$condo_images_max = 5;
for ( $i = 1; $i <= $condo_images_max; $i++ ) {
// Get image ID.
$image_id = get_field( 'gallery-image-' . $i );
// Check if image ID was found.
if ( $image_id ) {
// Output medium image in an li tag.
echo '<li>' . wp_get_attachment_image( $image_id, 'medium' ) . </li>';
}
} ?>
</ul>
If you need to be able to control the output of the image element and display it in the way you show in your question you can use:
...
if ( $image_id ) {
// Get image source.
$image = wp_get_attachment_image_src( $image_id, 'medium' );
// Check image source was found.
if ( $image ) {
echo '<li><img src="' . $image[0] . '" alt="Carousel Image" /></li>';
}
}
...
There is one issue in doing it this way to be aware of (and one of the reasons I suggested a repeater).
Let's say you have 6 image fields and a property is using all 6. The admin then decides to delete the first image so now the property has 5 images. The code will still work because we're checking an image was found before trying to output it but instead of showing all 5 images you'll only see 4 of them. Image #1 is empty and we've told it to stop looking after image #5.
I have this code to retrieve the image url for the images in a gallery and it works ok but i cannot figure out how i could get the caption for each image.
I tried searching all over but i cannot seem to put all the information out there together! Any suggestions on how i could retrieve the captions?
function show_related_gallery_image_urls( $content ) {
global $post;
// Only do this on singular items
if( ! is_singular() )
return $content;
// Make sure the post has a gallery in it
if( ! has_shortcode( $post->post_content, 'gallery' ) )
return $content;
// Retrieve all galleries of this post
$galleries = get_post_galleries_images( $post );
$image_list = <<<END
<div class="side_bar">
<div class="related">
<h3>Related Images</h3>
END;
// Loop through all galleries found
foreach( $galleries as $gallery ) {
// Loop through each image in each gallery
foreach( $gallery as $image ) {
$src = $image;
$image_list .= '<a href="' . $src . '" rel="' . get_the_title() . '">'
. '<img src="' . $src .'" />'
. '</a>';
}
}
$image_list .= '</div></div>';
// Append our image list to the content of our post
$content .= $image_list;
return $content;
}
add_filter( 'the_content', 'show_related_gallery_image_urls' );
I hope i explained myself well! Thanks!
This hasn't been tested by try it, I cleaned up some of your code a bit:
1) Combined the first 2 IF statements into 1
2) Used get_post_gallery() (Codex) which returns the src and the image ID. We use the image ID to return the caption, we can also get the description and more if we needed to.
3) Removed the containing Foreach Statement since both my method only returns 1 gallery, not multiple so no need to loop through.
function show_related_gallery_image_urls( $content ) {
global $post;
// Only do this on singular items
if( ! is_singular() || !has_shortcode( $post->post_content, 'gallery' ) )
return $content;
// Retrieve all galleries of this post
$galleries = get_post_gallery( $post, false );
$image_list = <<<END
<div class="side_bar">
<div class="related">
<h3>Related Images</h3>
END;
// Loop through each image in each gallery
$i = 0; // Iterator
foreach( $gallery['src'] as $src ) {
$caption = wp_get_attachment($gallery['id'][$i])['caption'];
$image_list .= '<a href="' . $src . '" rel="' . get_the_title() . '">'
. '<img src="' . $src .'" />'
. '<div class="caption">'
. $caption
. '</div>'
. '</a>';
$i++; // Incremenet Interator
}
$image_list .= '</div></div>';
// Append our image list to the content of our post
$content .= $image_list;
return $content;
}
add_filter( 'the_content', 'show_related_gallery_image_urls' );
function wp_get_attachment( $attachment_id ) {
$attachment = get_post( $attachment_id );
return array(
'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
'caption' => $attachment->post_excerpt,
'description' => $attachment->post_content,
'href' => get_permalink( $attachment->ID ),
'src' => $attachment->guid,
'title' => $attachment->post_title
);
}
On a sidenote, there is a gallery filter function where you can change how the gallery is displayed post_gallery Filter, here's a question that kind of shows how to edit it. There's also a great WordPress Stack Exchange where that may be helpful in the future!