Get all attachments from current page in Wordpress - php

I try to get all attachments from a current wordpress page. But my code only shows me the first result. What´s the issue?
My code
<?php
$attachments = get_children(array(
'post_parent' => $post->ID,
'post_status' => 'any',
'post_type' => 'attachment',
'post_mime_type' => 'image'
)
);
foreach($attachments as $att_id => $attachment) {
if (get_post_meta( $attachment->ID, '_bildnachweis', true )) {
$full_img_caption = get_post_meta( $attachment->ID, '_bildnachweis', true );
echo $full_img_caption; // Here I need more results, but the browser shows me only one.
}
}
?>
echo $full_img_caption; shows me only one result instead of three existing images for the page. There is a problem with my foreach loop?

I think you should use false instead of true in this line: get_post_meta( $attachment->ID, '_bildnachweis', true ) to get all values. true will only return the first value. https://developer.wordpress.org/reference/functions/get_post_meta/

I found a way that works:
<?php
//This will return the HTML source of the page as a string.
$htmlString = $post->post_content;
//Create a new DOMDocument object.
$htmlDom = new DOMDocument;
//Load the HTML string into our DOMDocument object.
#$htmlDom->loadHTML($htmlString);
//Extract all img elements / tags from the HTML.
$imageTags = $htmlDom->getElementsByTagName('img');
//Create an array to add extracted images to.
$extractedImages = array();
//Loop through the image tags that DOMDocument found.
foreach($imageTags as $imageTag){
//Get the alt text of the image.
$classText = $imageTag->getAttribute('class');
//Add the image details to our $extractedImages array.
$extractedImages[] = array(
'class' => $classText
);
}
?>
<div id="image-copyright" class="container">
<strong>Bildnachweis:</strong>
<?php
foreach($extractedImages as $image) {
$unsplittedImage = $image["class"];
$imageID = explode("wp-image-", $unsplittedImage)[1];
$full_img_caption = get_post_meta( $imageID, '_bildnachweis', true );
if ($full_img_caption) {
echo "<span class='single-author'>". $full_img_caption ."</span>";
}
?>
<?php
}
?>
</div>

Related

Loop All Attachment URL In Posts Wordpress

I Want to loop all attachment url and save new html.
Sorry, I only script kiddies. I only understand some code.
This my script php
function get_all_image_clickable($content) {
global $post;
$args_img = array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
"what_to_show" =>"posts",
"showposts" =>-1,
"post_mime_type" =>"image"
);
$attachments = get_posts($args_img);
$i = 0;
$dom = new DOMDocument('UTF-8');
#$dom->loadHTML( utf8_decode($content) ); // Decode to simple ISO to avoid accent errors
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
if( count($images) > 0 ) {
foreach ($images as $image) {
$width = $image->getAttribute('width'); // get the widths of each image
if( $width >= 860) { // if image is less than 860, add their old classes back in plus our new class
$clone_img = $image->cloneNode(); //clone node images
// Create DIV container
foreach ($attachments as $attachment) {
$parent = get_post($post->post_parent);
if($parent->post_status == "publish"){
$image_wrap = $dom->createElement('a');
$image_wrap->setAttribute('class', 'img-gallery' );
$image_wrap->setAttribute('href', get_attachment_link($attachment->ID));
}
$i++;
wp_reset_postdata();
}
$image_wrap->appendChild( $clone_img ); // Add to image to new container
$image->parentNode->replaceChild( $image_wrap, $image ); // Replace img object with all new elements
}
} // end if count
$content = $dom->saveHTML();
}
return $content;
}
add_filter( 'the_content' , 'get_all_image_clickable' , 15 );
i want to get all attachment url on its own image.
Sorry, my english bad.

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 );

WordPress replace all instances of [vc_single_image] shortcode with img src

im updating my WordPress website and removing the https://wpbakery.com/ editor and I'm wanting to remove the markup generated by the plugin.
This plugin https://codecanyon.net/item/shortcode-cleaner-clean-wordpress-content-from-broken-shortcodes/21253243 I'm using will remove all shortcodes with no problem except one. It's removing images.
On closer inspection images are posted on the backend using the below shortcode
[vc_single_image image="10879" img_size="large" add_caption="yes" alignment="center"]
And I want to update all references to use HTML instead
<img src="IMGURL">
However, I'm not sure about the right way to do it, any advice, please?
There is a regular expression replace in MySQL 8, but if you don't have that, you could do it with PHP.
$query = new WP_Query( [-- whatever posts you want--] );
while ( $query->have_posts() ) {
$query->the_post();
$content = get_the_content();
preg_match('/\[vc_single_image image="(\d+)" img_size="(\w+)"[^\]]*\]/', $content, $matches);
if( isset($matches[1]) ) {
$url = wp_get_attachment_image_url( (int) $matches[1], $matches[2] );
$img = sprintf( '<img src="%s" />', $url );
$new_content = str_replace( $matches[0], $img, $content );
wp_update_post( [ 'ID' => get_the_ID(), 'post_content' => $new_content] );
}
}
Here Is the updated answer to update all images in the post/page content. The above code finds the first image of the content and update that.
// Args for the WP_Query
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'post__in' => array(5824),
'orderby' => 'post__in'
);
// Execute WP_Query with args
$query = new WP_Query( $args );
// Start the Loop
while ( $query->have_posts() ) {
$query->the_post();
// Get Page/Post content
$content = apply_filters('the_content', $content);
// Get the vc_single_image count from the post
$found_keyword = substr_count( $content,"vc_single_image" );
// Start loop to replace all elements from the content
for ($i=0; $i < $found_keyword; $i++) {
// Get the position of vc_single_image shortcode with Image ID and Image Size
preg_match( '/\[vc_single_image image="(\d+)" img_size="(\w+)"[^\]]*\]/', $content, $matches );
// Check shotcode are exist on loop
if( isset( $matches[1]) ){
// Get the Image ur by Image id and Size
$url = wp_get_attachment_image_url( (int) $matches[1], $matches[2] );
$img = sprintf( '<img src="%s" />', $url );
// Replce shortcode with <img> tag
$content = str_replace( $matches[0], $img, $content );
}
}
// Update post content with updated content with <img> tag
wp_update_post( [ 'ID' => get_the_ID(), 'post_content' => $content] );
}
// END the Loop

PHP wordpress - use get_attached_media image, if featured image doesn't exist

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;
}

Display WordPress post content images and text separately

I'm looking at the WordPress blog and I'm trying to figure out how to display the image and text separately when displaying the content. The reason I want to do this is because I want to create a custom layout, and I need to be able to move the image around without grabbing all the text at the same time. Does anyone have any idea on how to do this?
Example of what i've already got: (UPDATED)
<?php
require('blog/wp-blog-header.php');
?>
<?php
$args = array( 'numberposts' => 2, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
$postslist = get_posts( $args );
echo '<ul id="latest_posts">';
foreach
($postslist as $post) : setup_postdata($post);
echo get_content_without_tag( apply_filters( 'the_content', get_the_content() ), 'a' );
$image = get_tag_without_text( apply_filters( 'the_content', get_the_content() ), 'a' );
?>
<li>
<strong>
<?php the_date(); ?>
</strong>
<br />
<?php the_title(); ?>
<p>
<?php echo $image[0]; ?>
</p>
</li>
<?php endforeach; ?>
</ul>
ERROR:
Warning: DOMDocument::saveHTML() expects exactly 0 parameters, 1 given
in
/hsphere/local/home/poulaum/isosec.co.uk/blog/wp-includes/functions.php
on line 4874
and image to show what the above code displays:
You can make use of featured images. This featured image will not be included in post content. However, if you already have your images included in post content, then you need to strip the post content down in two parts, as you've said in your question.
I have two functions, one that returns all the images (or any html tag content) from the content and one function that returns the text without the desired tag/images. Both of these functions uses DOMDocument
The first function get_content_without_tag() returns the content which has been stripped from images. There are two parameters
$html -> The text with images to be stripped, in this case, use apply_filters( 'the_content', get_the_content() ) to use the post content
$tag -> The name of the tag to strip out, in this case, 'a' as a tags hold images
Here is the function
function get_content_without_tag( $html, $tag )
{
// Return false if no html or tag is passed
if ( !$html || !$tag )
return false;
$dom = new DOMDocument;
$dom->loadHTML( $html );
$dom_x_path = new DOMXPath( $dom );
while ($node = $dom_x_path->query( '//' . $tag )->item(0)) {
$node->parentNode->removeChild( $node );
}
return $dom->saveHTML();
}
You would then use this in place of the_content() where you would need to display text only, stripping out the complete <a/> tag in which the images are as follows
echo get_content_without_tag( apply_filters( 'the_content', get_the_content() ), 'a' )
The second function, get_tag_without_text() returns the content between the desired tag, in your case, images. The parameters are exactly the same as the first function. Here is the function
function get_tag_without_text( $html, $tag )
{
// Return false if no html or tag is passed
if ( !$html || !$tag )
return false;
$document = new DOMDocument();
$document->loadHTML( $html );
$tags = [];
$elements = $document->getElementsByTagName( $tag );
if ( $elements ) {
foreach ( $elements as $element ) {
$tags[] = $document->saveHtml($element);
}
}
return $tags;
}
This function returns an array of images should you use a tags, so, to display the first image, use the function as follow:
$image = get_tag_without_text( apply_filters( 'the_content', get_the_content() ), 'a' );
echo $image[0];
EDIT
The code above is was only tested with WP_Query and not with get_posts. I have fixed a few bugs in the code above and also in your code to make it work with get_posts
Here is a working example of your code. (Just remember to update the the functions with the new ones above)
<?php
$args = array(
'numberposts' => 2,
'post_status' => 'publish',
'post_type' => 'post',
'orderby' => 'date'
);
$postslist = get_posts( $args );
echo '<ul id="latest_posts">';
foreach ( $postslist as $post ) {
setup_postdata($post);
$content = get_content_without_tag( $post->post_content, 'a' );
$image = get_tag_without_text( $post->post_content, 'a' );
if ( $content )
echo apply_filters( 'the_content', $content );
?>
<li>
<strong>
<?php the_date(); ?>
</strong>
<br />
<a href="<?php the_permalink(); ?>" title="<?php the_title();?>">
<?php the_title(); ?>
</a>
<?php
if ( $image ) {
?>
<p>
<?php echo apply_filters( 'the_content', $image[0] ); ?>
</p>
<?php
}
?>
</li>
<?php
}
echo '</ul>';

Categories