how to make query to get attachment image url in wp - php

i was using database to get id=1 for example - location = image url
it was like that
include 'config.php';
$GetPicId = $_GET["pid"]; // Picture ID from Index page
$query=mysql_query("SELECT * FROM fbcover WHERE id=$GetPicId") or die(mysql_error());
$result=mysql_fetch_array($query);
$PicLocation =$result['location'];
now i would like to using wordpress
iam trying to get attachment image url by using post id for example
include 'config.php';
$GetPicId = $_GET["pid"]; // Picture ID from Index page
$query=mysql_query("SELECT * FROM wp_posts WHERE id=$GetPicId") or die(mysql_error());
$result=mysql_fetch_array($query);
$PicLocation =$result['guid'];
and i always get this msg " failed creating formpost data "
how can i get attachment image url in
$PicLocation =$result['location'];
i really need help ... thanks

<?php
remove_all_filters('posts_orderby');
query_posts('showposts=3&post_type=image&orderby=rand');
global $more; $more=0;?>
<?php if (have_posts) : while (have_posts()) : the_post(); global $more; $more=0;?>
<?php
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'orderby' => 'rand', 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
echo '';
// count number of available images and change if less than the specified limit
foreach ($attachments as $post) {
setup_postdata($post);
$image = wp_get_attachment_image_src( $post->ID, 'thumbnail', false );
echo '<span class="media">'.get_the_title().'</span>';;
}
echo '';
}
?>
<?php endwhile; endif; ?>
Courtesy: http://wordpress.org/support/topic/wordpress-query-for-attachments

If you using Wordpress then you should use build in function for it. If you have attachment id use wp_get_attachment_url($att_id) to get link or
wp_get_attachment_image_src($att_id) to get path to file.
Here you have good examples of using get_posts to achieve what you want:
http://codex.wordpress.org/Template_Tags/get_posts
Show all attachments
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => null );
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $post ) {
the_attachment_link( $attachment->ID , false ); //for url
$path = wp_get_attachment_image_src($attachment->ID, 'your-size'); //for direct path to image
}
}
Show attachments specific post
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'any', 'post_parent' => $post_id );
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
the_attachment_link( $attachment->ID , false ); //for url
$path = wp_get_attachment_image_src($attachment->ID, 'your-size'); //for direct path to image
}
}
P.S.
If you want to create batch script or something out of site but with access to all WordPress "magic" add this at beginning:
define('BASE_PATH', dirname(__FILE__).'/');
define('WP_USE_THEMES', false);
if ( !defined('ABSPATH') ) {
require_once(BASE_PATH.'wp-load.php');
}
...and you will have access to all functions I mention above. Lookout on paths to wp-load.php file.

Related

Finding attachment page URL of/from an image url

I'm using the below code to get all image URL's attached to a post.
global $post;
$thumbnail_ID = get_post_thumbnail_id();
$images = get_children( array('post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
if ($images) :
foreach ($images as $attachment_id => $image) :
$img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); //alt
if ($img_alt == '') : $img_alt = $image->post_title; endif;
$big_array = image_downsize( $image->ID, 'large' );
$img_url = $big_array[0];
endforeach; endif; }
The output I get is something like this:
https://www.example.com/wp-content/uploads/2019/01/image.gif
What I need to find is the attachment page URL for this image which will be something like this https://www.example.com/post-name/image-22
I tried using wp_get_attachment_image, but the output wasn't what I needed.
any idea how can i do that?
You are looking for get_attachment_link to return a pretty link you need to make sure your permalink structure is set to pretty links.
https://codex.wordpress.org/Function_Reference/get_attachment_link
Example from page:
<?php
$attachment_id = 1; // ID of attachment
$attachment_page = get_attachment_link( $attachment_id );
?>
<?php echo get_the_title( $attachment_id ); ?>

Wordpress: Display image attachments from child pages of a specific page

I am trying to display all image attachments on the child pages of a specific parent page, i.e. all the pictures on Pages 10, 11 and 12.
Projects (Page ID: 5)
- Project 1 (Page ID: 10)
- Project 2 (Page ID: 11)
- Project 3 (Page ID: 12)
This is what I have so far, and it works to display all images on the site:
<?php
$args = array(
'post_parent' => 0,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
?>
However, if I add the post parent ID (5), nothing comes up:
<?php
$args = array(
'post_parent' => 5,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
?>
Any suggestions would be really helpful!
I think get_children() return objects from a single parent post or all (passing 0 as value).
You may try a nested foreach to get all post children first, then query attachment page by page. Here is an untested sample, but it gives you an idea:
<?php
$subpages_args = array(
'post_parent' => 5,
'post_type' => 'page',
'numberposts' => -1
);
$sub_pages = get_children( $subpages_args );
foreach( $sub_pages as $subpage_id => $sub_page) {
$args = array(
'post_parent' => subpage_id,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
}
?>
Good luck :)
Here is an SQL Query based solution. Copy following function in your theme's functions.php
function get_children_page_attachments($parent_id) {
global $wpdb;
// just a precautionary typecast and check
$parent_id = intval( $parent_id );
if( empty($parent_id) ) return [];
$query = "SELECT ID FROM {$wpdb->posts} P WHERE post_type='attachment' AND P.post_parent IN (SELECT ID FROM {$wpdb->posts} WHERE post_parent={$parent_id} AND post_type='page' )";
return $wpdb->get_results($query, 'ARRAY_A');
}
Once you have above function in your functions.php, then you can use it like this:
// for example the parent page id is 16
$image_ids = get_children_page_attachments(16);
foreach($image_ids as $image_id) {
$image = wp_get_attachment_image($image_id['ID'], 'full');
}

wp returns "wrong" image ID

well,
Code dosent make mistakes so i have something i dont see here...
I have following code on wp page:
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $pages->ID
);
$images = get_posts($args);
$attachment_id = $images[0]->ID;
$i = wp_get_attachment_image_src($attachment_id, $size);
$p = array_values($i)[0];
if (has_post_thumbnail()) {
the_post_thumbnail($size);
} else {
} ?>
It, works, in a way.
it will return a image url and i can use it to show images on page, anyhow the ID it return seems to be somewhat random.
I have the right ID for page to look for images in $pages
i would need to return first image of that page.
I would assume, array[0] would be first image of page, but obviously it is not since it returns very strange pictures from another page, which has nothing to do with this page.
I'm not sure but seems you are doing it wrong. :)
Why can't you use
echo get_the_post_thumbnail( $post_id, 'thumbnail', array( 'class' => 'alignleft' ) )
or
get_the_post_thumbnail_url( int|WP_Post $post = null, string|array $size = 'post-thumbnail' )
or
get_post_thumbnail_id( $post_id );
Please Try :
global $post;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $pages->ID
);
$images = get_posts($args);
$attachment_id = $images[0]->ID;
$i = wp_get_attachment_image_src($attachment_id, $size);
$p = array_values($i)[0];
if (has_post_thumbnail($post->ID )) {
the_post_thumbnail($size);
} else {
}

Wordpress get URL of a post from its attachment

I am adding an image from media in every single post that are created.
To get the attached image and url of that post, I am implementing this code:
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => 5,
'post_status' => null,
'post_parent' => 'any', // any parent
);
$attachments = get_posts($args);
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
setup_postdata($attachment);
$v =$attachment->ID;
$imageurl = wp_get_attachment_url($v);
$postlink = get_permalink($v);
}
The above code works fine for retrieving image url. My question is how do I pass post ID in get_permalink() to make sure that I get link of that post. I know that passing $v in get_permalink() is wrong.
There is a code spinet to print attachment posts.
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => 5,
'post_status' => 'inherit',
'post_parent' => 'any', // any parent
);
$loop = new WP_Query($args);
while ( $loop->have_posts() ) : $loop->the_post();
global $post;
echo '<pre>';
print_r($post);
echo '</pre>';
endwhile; wp_reset_query();
Its depending which ID you are looking for inside the loop
$post-ID : That return the post ID for attachment post.
$post->post_parent : It returns the current attachment post parent post ID.

Trying to get an attachment from a post in a Wordpress loop but getting all, from all posts

First of all - this is a question mainly about the loop™. I'm also having problems with the attachment thing, but that is somehow secondary since there are snippets around there I think could be useful.
Ok, so this is want I want to do in a front page:
get 7 posts from custom post type 'portfolio'
only with the first one, get an specific attachment (in any possible way, be it filename, order in the media manager... whatever is the best, more clean way)
with the other 6, just get the_post_thumbnail() and little more.
Now, I have this:
<?php
$args = array (
'post_type' => 'portfolio',
'order' => 'DESC',
'posts_per_page' => 7
);
$query = new WP_Query( $args );
$first_post = true; /* we will take the latest work first */
?>
<?php if ( $query->have_posts() ) : ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php
if ($first_post):
$first_post = false;
?>
<div> /* This is the div for the first item */
<?php /* let's take the first attachment */
$args = array(
'post_type' => 'attachment',
'numberposts' => 1,
'order' => 'DESC'
);
$attachments = get_posts( $args );
if ( $attachments ) :
foreach ( $attachments as $attachment ) :
echo wp_get_attachment_image( $attachment->ID, 'full' );
endforeach;
endif;
?>
</div>
<?php else: ?>
/* Do something with the other 6 posts and their post_thumbnail */
<?php endif ?>
<?php endwhile; ?>
And now for the questions:
First and foremost: if I set 'numberposts' to all (-1) when trying to recover the attachment, I get ALL attachments from ALL 'portfolio' posts. Shouldn't I be interacting only with the current post (the_post())? I can't quite grasp the concept of the loop here, this is the main question.
That code won't get me the first attachment, even if it's placed in the first place in that post's media manager.
Should I go for secondary or nested loops? I've read and re-read the codex and other tutorials but still can't wrap my head around it.
Many thanks!
used this code :
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
) );
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 $thumbimg;
}
}
User Shakti Patel gave me the key to the answer, but didn't really answer my question about the loop so here it goes:
The problem was with get_posts. It actually runs a parallel query to the main one without taking into account the current step of the loop. So we have to ask it for the attachments of the current post, which since we're in the loop is stored within $post->ID. So knowing that, we have to request the first attachment for the current post like this:
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 1,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
);
$attachments = get_posts( $args );
That way we specify what is the post from which we'll get the first attachment, and while we're on it, exclude the post thumbnail.
I don't know if this is the best way since we're already on a loop and we shouldn't need a new query, shouldn't we be able to retrieve that attachment without the get_posts bit?
Anyway, for more info on get_posts (read while not half asleep): http://codex.wordpress.org/Template_Tags/get_posts

Categories