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

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

Related

I want to print the meta_value of all with the key "post_views_count" from the post_meta table

I want to print (meta_value) from all fields
"Post_views_count" from table (post_meta) But provided that this happens in every category.
I want to count every visit inaide selected category , and in the end appear the name of category and every category generate visitors inside it .
This is the code that i used it and work good but the page are too slowly due to recurrent queries
<?php
$args = array(
'orderby' => 'name',
'parent' => 0,
'depth' => 0
);
// Extract all categories
$categories = get_categories( $args );
foreach ( $categories as $category ) {
// Extract all posts within each category
$args = array(
'cat' => $category->term_id,
'orderby' =>'post_date',
'post_type' => 'post',
'posts_per_page' => '-1',
);
$query = new WP_Query( $args );
// Views variable
$allview_cat = 0;
if ( $query->have_posts() ) {
$posttype = get_post_type(get_the_ID());
while ( $query->have_posts() ) {
$query->the_post();
$do_not_duplicate[] = $post->ID;
// Query that extracts all fields containing post_views_count + post id
$post_id = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE (meta_key = 'post_views_count' AND post_id = $post->ID );");
$post_id = array_map(function($item){
return $item->{'meta_value'};
}
,$post_id);
foreach($post_id as $m_key => $m_value) {
$allview_cat = $m_value + $allview_cat ."<br>";
}
} // end while
} // end if
// Views variable
echo $allview_cat;
}
?>
<?php
$args = array(
'orderby' => 'name',
'parent' => 0,
'depth' => 0
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$cat_id = $category->term_id;
$args_post = array(
'cat' => $cat_id,
'post_type' => 'post',
'posts_per_page' => '-1',
);
$query = new WP_Query( $args_post );
$allview = array();
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$post_id = get_the_ID();
if ( !isset( $allview[$cat_id] ) {
$allview[$cat_id] = 0;
}
$post_views_count = get_post_meta( $post_id, 'post_views_count' );
$allview[$cat_id] = (int)$allview[$cat_id] + (int)$post_views_count;
}
}
}
//display results
foreach ( $allview as $cat => $value ) {
echo $cat . ' = ' . $value;
}
?>

WordPress post count : X out of Y?

I'm working on a theme with CPT.
In single-cpt.php, I want to show the post number out of the total posts.
I managed to show the total ok posts using :
<?php $args = array(
'post_type' => 'cpt_type',
'post_status' => 'published',
'numberposts' => -1
);
echo $num = count( get_posts( $args ) ); ?>
and it returns the total of posts for that CPT type. So, on each single cpt, I got the total number.
What I would like, is to have "post number" / "total posts". Example : 7/21, and when I go o the following post : 8/21 and so on...
So, how could I get each single post to have a "number"?
Thanks!
Paste this in functions.php:
function get_total_number_of_posts( $post ) {
$posts = get_posts( array(
'post_type' => $post->post_type,
'posts_per_page' => -1
) );
return count( $posts );
}
function get_current_post_index( $post ) {
$posts = get_posts( array(
'post_type' => $post->post_type,
'posts_per_page' => -1
) );
$index = 0;
foreach ( $posts as $p ) {
$index++;
if ( $p->ID === $post->ID ) {
break;
}
}
return $index;
}
and then in your single.php file:
global $post;
$total_posts = get_total_number_of_posts( $post );
$current_post = get_current_post_index( $post );
echo "You are viewing {$current_post} out of {$total_posts}";

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

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.

Wordpress: Get images of current post

i'm trying to get all images of a post using this method:
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
}
return $images;
}
unfortunately, this will get all images ever uploaded, not just those associated to the current post. i found this post using *get_children*, but it doesn't work either. any ideas?
ps: i running the code when a post created/updated
You can try
<?php
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->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 '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
}
?>
Read more here.
Make sure $post->ID is not empty.
If this is still not working you can try Extracting Images from the Page / Post content. More details here
Try it by adding a hook in your functions.php to fire after post/page has been created/updated and wrap your code inside that function as given bellow
add_action( 'save_post', 'after_post_save' );
function after_post_save( $post_id ) {
if ( 'post' == get_post_type($post_id) ) // check if this is a post
{
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post_id
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
}
return $images; // End of function and nothing happens
}
}
}
Remember, basically it'll do nothing by returning the $images array at the end of your function unless you do something with the images.
Note: The wp_get_attachment_image_src function returns an array which contains
[0] => url // the src of image
[1] => width // the width
[2] => height // the height
So in your $images array it will contain something like this
array(
[0] => array([0] => url, [1] => width, [2] => height), // first image
[1] => array([0] => url, [1] => width, 2] => height) // second image
);

Categories