Loop All Attachment URL In Posts Wordpress - php

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.

Related

Woocommerce Product Creation Automation

I'm trying to develop a program that creates woocommerce products based on the media that were uploaded in the wordpress library.
All products have the same settings, the only things that change is the photo and the download.
With some research I managed to develop the following code that is running in functions.php:
add_action( 'init', 'product_automation');
function product_automation() {
$loopProdutos = new WP_Query([
'post_type' => 'product',
'posts_per_page' => -1
]);
$arrayProduct = (array) $loopProdutos->posts;
// Picking up all the products from the store
$idImgProduct = [];
foreach($arrayProduct as $product) {
$produto = wc_get_product($product->ID);
$idImgProduct[] = $produto->image_id;
}
// Taking all photo IDs from existing products
$loopImagens = new WP_Query([
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'post_date',
'order' => 'desc',
'posts_per_page' => -1,
'post_status' => 'inherit'
]);
$arrayImg = (array) $loopImagens->posts;
// Taking all uploaded photos
$idImg = [];
foreach($arrayImg as $image) {
$idImg[] = $image->ID;
}
// Getting all uploaded photo IDs
$newIds = array_diff($idImg, $idImgProduct);
// Seeing which IDs do not yet exist
$newProductsArray = [];
// Array with new products
foreach($newIds as $idImagem) {
$objProduct = new WC_Product_Simple();
$objProduct->set_name("Foto");
$objProduct->set_status("publish");
$objProduct->set_catalog_visibility('visible');
$objProduct->set_price(15.00);
$objProduct->set_regular_price(15.00);
$objProduct->set_sold_individually(true);
$objProduct->set_image_id($idImagem);
$objProduct->set_downloadable(true);
$objProduct->set_virtual(true);
// Create a simple product
$src_img = wp_get_attachment_image_src( $idImagem, 'full');
$img_meta = wp_get_attachment_metadata( $idImagem, false );
$file_title = $img_meta['image_meta']['title'];
$file_url = reset($src_img);
$file_md5 = md5($file_url);
$download = new WC_Product_Download();
$download->set_name($file_title);
$download->set_id($file_md5);
$download->set_file($file_url);
$downloads[$md5_num] = $download;
$objProduct->set_downloads($downloads);
// Code to automatically add download link to product
$newProductsArray[] = $objProduct;
}
for ($i = 0; $i < count($newProductsArray); $i++) {
$newProductsArray[$i]->save();
}
//Loop to save each new product
}
The code works great. The problem is that it creates more products than anticipated.
For example, if I have 10 photos in my library, it creates 16 or 20 products (each photo generates more than one product).
I cannot find the error. Need help.😅
Here you go, I've tested it and it seems to work, apart from "attaching the image to the post" (I mean, it shows as product featured image, but under Media it says it's not attached to anything and you can't "detach").
I found another hook, which should work better than wp_handle_upload, and also fixed a couple of bugs (image title and downloads array):
add_action( 'add_attachment', 'bbloomer_product_automation', 9999 );
function bbloomer_product_automation( $image_id ) {
$product = new WC_Product_Simple();
$product->set_name( 'Foto' );
$product->set_status( 'publish' );
$product->set_catalog_visibility( 'visible' );
$product->set_price( 15 );
$product->set_regular_price( 15 );
$product->set_sold_individually( true );
$product->set_image_id( $image_id );
$product->set_downloadable( true );
$product->set_virtual( true );
$src_img = wp_get_attachment_image_src( $image_id, 'full' );
$file_title = get_the_title( $image_id ); // CORRECT GET IMAGE TITLE
$file_url = reset( $src_img );
$file_md5 = md5( $file_url );
$download = new WC_Product_Download();
$download->set_name( $file_title );
$download->set_id( $file_md5 );
$download->set_file( $file_url );
$downloads[$file_md5] = $download; // BUG FIXED
$product->set_downloads( $downloads );
$product->save();
}

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

Get all attachments from current page in Wordpress

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>

php request for images and fill blanks with a default image

I have function that retrieves the images uploaded by each user. The limit per user is 5 images and I want to display a default image to fill the blanks upto 5 if they have less than 5 uploads. How can I achieve this?
function display_images() {
$imgs = get_images();
$html = '<div class="myImages">';
foreach($imgs as $img) {
$html .= '<div class="myImageContainer"><img src="'. $img .'"/></div>';
}
$html .= '</div>';
return $html;
}
function get_images() {
global $current_user;
get_currentuserinfo();
$args = array(
'author' => $current_user->ID,
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => 5,
'orderby' => 'date'
);
$query_images = new WP_Query( $args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
}
return $images;
}
You have to check for current length of total images:
function display_images() {
$imgs = get_images();
$html = '<div class="myImages">';
foreach($imgs as $img) {
$html .= '<div class="myImageContainer"><img src="'. $img .'"/></div>';
}
if (count($imgs)<5) {
for($i=0; $i<(5-count($imgs)); $i++) {
$html .= '<div class="myImageContainer"><img src="MY_BLANK_IMAGE_LINK"/></div>';
}
}
$html .= '</div>';
return $html;
}

Modify Wordpress plugin to show posts by category instead of id#

I am using this Wordpress plugin: http://wordpress.org/plugins/carousel-of-post-images/
It shows a slider of posts & displays the featured image.
It is currently set to show posts by id which need to be individually entered into the shortcode. Is it possible to show posts by category instead so that I can set the category of the post and see only that category in the slider?
Here is all the code that I believe is responsible.
function copi_carousel_get_images($size = 'medium' , $orderby, $posts, $count, $class = ''){
global $post;
$att_array = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => $orderby,
'numberposts' => $count,
);
$postlist = explode(",",$posts);
$sizes = explode(",", $size);
$html = '';
if (count($sizes) == 2)
{
$width = $sizes[0];
$height = $sizes[1];
$size=$sizes;
}
else
{
$width = get_option($size.'_size_w');
$height = get_option($size.'_size_h');
}
foreach($postlist as $postid)
{
if ($postid != '')
$att_array['post_parent'] = $postid;
$attachments = get_posts($att_array);
if (is_array($attachments)){
foreach($attachments as $att){
$image_src_array = wp_get_attachment_image_src($att->ID, $size);
$url = $image_src_array[0];
if ($url != "")
{
$prefix = '<li><a href="'.get_permalink($att->post_parent).'">';
$suffix = "</a></li>";
$caption = $att->post_excerpt;
if(function_exists('thumbGen'))
$url = thumbGen($url, $width, $height, 'return=1');
$image_html = '<img src="%s" height="'.$height.'" alt="%s">';
$html .= $prefix.sprintf($image_html,$url,$caption,$class).$suffix;
}
}
}
}
return $html;
}
function show_wp_copi_carousel($atts){
$skin = 'tango';
$div='post-carousel';
$imagesize = 'medium';
$orderby = 'rand';
$postid = '';
$count='10';
if (isset($atts['skin']))
$skin = $atts['skin'];
if (isset($atts['imagesize']))
$imagesize = $atts['imagesize'];
if (isset($atts['orderby']))
$orderby = $atts['orderby'];
if (isset($atts['postid']))
$postid = $atts['postid'];
if (isset($atts['count']))
{
$count = $atts['count'];
I do this with Coda slider.
First include the script in the head:
<script src="js/jquery.coda-slider-3.0.js"></script>
<script>
$(function(){
/* Here is the slider using default settings */
$('#slider-id').codaSlider({
autoSlide:true,
autoHeight:false
});
});
</script>
Then I used the loop:
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div class="coda-slider" id="slider-id">
<?php
$args = array('category' => 15, 'numberposts' => 4, 'order'=> 'ASC');
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post); ?>
<img src="<?php echo $image[0]; ?>"/>
<?php endforeach; ?>
</div>
This should work!
Note: To show post information, just include "the_post" in the loop or whatever content you want to display, the slider script will take care of the rotation.
Also, this needs to be used in a template.

Categories