wp returns "wrong" image ID - php

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

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

Wordpress get attachment image caption

I tried to get attachment meta caption value as mentioned here, but couldn`t get any output. Other meta arrays like [created_timestamp] or [iso] gave their values.
$img_meta = wp_get_attachment_metadata( $id );
echo $img_meta[image_meta][caption];
This issue happens to both [caption] and [title]. Any help is much appreciated.
The caption and title you are looking to get from wp_get_attachment_metadata are not the title and caption you add in WordPress they are meta data from the actual image itself. To get the WordPress data use something like this (assuming $id is the id of your image).
$image = get_post($id);
$image_title = $image->post_title;
$image_caption = $image->post_excerpt;
Since WordPress 4.6.0 there is get_the_post_thumbnail_caption($post) which gets you the caption for the specified post.
put this in your functions.php file:
function show_caption_image($type='title'){
global $post;
$args = array( 'post_type' => 'attachment', 'orderby' => 'menu_order', 'order' => 'ASC', 'post_mime_type' => 'image' ,'post_status' => null, 'numberposts' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
$alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
$image_title = $attachment->post_title;
$caption = $attachment->post_excerpt;
$description = $image->post_content;
}
}
return $type == 'title' ? $image_title : $caption.$description;
}
and below the image in your theme, or wherever you prefer to put it, usually in the single.php file:
<?php if ( has_post_thumbnail() ) :
?>
<span class="image main"><img src="<?php echo get_the_post_thumbnail_url()?>" alt="<?php echo get_the_title()?>" /><i><?php echo show_caption_image();?></i></span>
<?php endif; ?>

how to make query to get attachment image url in wp

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.

Quickest way to reference a Wordpress code snippet

This question is about tidying up code and better management of said code butI'm a complete novice when it comes to PHP so would appreciate a little help.
I have this code:
<?php
$thumb_id = get_post_thumbnail_id(get_the_ID()); // gets the post thumbnail ID
$args = array(
'order' => 'ASC',
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'exclude' => $thumb_id
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo wp_get_attachment_image($attachment->ID, 'full', false);
}
}
?>
What it does isn't important for reference, the above code gets random images from a Wordpress post randomly generates one of them in a DIV. I want this functionality across many templates but I don't want to cram my PHP files with it as my files will get messy and inefficiently large.
2 questions.
Do I need to change the code above in order to put it within functions.php?
How can I reference the above code (that will be within my functions.php) using a short one liner that I can reuse across many different templates?
You may like to try putting the snippet in to a function, inside functions.php, and passing it a few parameters, allowing the usage to be more flexible.
Untested, but this takes an array of options, and overwrites the default values (e.g for changing the order or orderby etc on a per-use basis). As an optional parameter you can pass a post_id, in case you want to query a post that isn't the current one.
It also returns an array of rather than outputs them directly, which can be seen as the preferred way of working with functions.
// functions.php
function get_random_post_image($options=array(), $post_id=NULL) {
if($post_id != NULL) :
$thumb_id = get_post_thumbnail_id($post_id);
else :
$thumb_id = get_post_thumbnail_id(get_the_ID());
endif;
$default_args = array(
'order' => 'ASC',
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'exclude' => $thumb_id
);
// merge custom options
$args = array_merge($default_args, $options);
$attachments = get_posts($args);
if ($attachments) {
$images = array();
foreach ($attachments as $attachment) {
$images[] = wp_get_attachment_image($attachment->ID, 'full', false);
}
return $images;
}
return false; // or, return default image/placeholder
}
// and within your template/posts:
if(function_exists('get_random_post_image')) :
$images = get_random_post_image(array('order'=>'DESC')); // overwrite `ASC`
if($images) :
foreach($images as $img) {
echo '<div class="post-img"> ' . $img . '</div>';
}
else :
echo 'No images!';
endif;
endif;
not perfect; but you could extend it easily enough.
1. You need to get out the <?php and ?> if you already put your code inside those tags
example functions.php:
<?php
blah blah
....
// your code here
$thumb_id = get_post_thumbnail_id(get_the_ID()); // gets the post thumbnail ID
$args = array(
'order' => 'ASC',
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'exclude' => $thumb_id
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo wp_get_attachment_image($attachment->ID, 'full', false);
}
}
// be careful, only one "?>" in the file, no nested "<?php ?>" blocks
?>
2. Use include(), include_once(), require() or require_once() and save your function in another file, so you can reference that file.
random_img.php
<?php
$thumb_id = get_post_thumbnail_id(get_the_ID()); // gets the post thumbnail ID
$args = array(
'order' => 'ASC',
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'exclude' => $thumb_id
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo wp_get_attachment_image($attachment->ID, 'full', false);
}
}
?>
functions.php
<?php
blah blah
....
include ("random_img.php")
?>

Categories