Wordpress get attachment of post doesn't work - wordpress

I'm trying to retrieve all the attachment of a specific post, but it doesn't work for the moment. Here is the code :
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $id
);
$attachments = get_posts($args);
Where Id is the id of my post. I've tried also with new WP_Query() but it didn't worked neither. Both ways return an empty result.
Does anyone have an idea what I'm doing wrong here ?
Thanks
EDIT
Ok, I think I know what's going wront.
When using this arguments for the get_posts function, it will return the images uploaded through the "Add a media" button in the specific post.
So basically, let's say that on my first post, I've uploaded all the images I would need for all my future post. If I apply the request on the first post, I will retrieve all the images, even the one that I don't use in this post.
If I apply this function to another post, because I didn't uploaded any file in this post, the function will retrieve an empty array.
Does anyone have an idea how I can retrieve all the images used in a specific post ? So not only uploaded, but really integrated into the post or added to a custom field ?
Thanks

When using get_posts to fetch attachments, you need to set post_status to inherit. Also, check out the get_children function:
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => -1,
'post_status' => 'inherit',
'post_parent' => $id
);
$attachments = get_children( $args );

Case: using ACF, I created an repeater field 'resort_pics' for my gallery, which has 2 fields 'picture_title' as text and 'picture' as an picture type.
Then happily uploaded 100 photos, some of them were same for several posts so I only clicked those from uploaded gallery (I will use term of "referenced images" for those).
Problem : then one happy day I noticed all "referenced images" are missing in our api.
Cause :
As noted at documentation comment from 'Uriahs Victor' (https://developer.wordpress.org/reference/functions/get_attached_media/)
Important to note that this function only returns the attachments that
were first uploaded/added to the post. Uploading an image to Post A(ID
1) and then adding that image later to Post B(ID 2) would give an
empty array if the following code was used:
$media = get_attached_media( 'image', 2 );
var_dump( $media );
Real cause :
Real source of all this problem is The thing that information about "reference images" are not stored in 'wp_posts' table but are actually stored in 'wp_postmeta', so by just querying 'wp_posts' table or using get_attached_media() which only looks there also you will not get all attachements for post.
Solution :
Lets take an example of post with ID - $postId which has defined
repeater - 'resort_pics', field in repeater with image 'picture'. (created with ACF plugin)
First get all attachements for our post (resort) (including images/pdfs and so on) with classic way (can be also used 'get_attached_media'):
$images = $wpdb->get_results("select ID,guid from wp_posts where post_parent = " . $postId . " and `post_type`= 'attachment'");
where guid is 'url' to an attachement, lets index those in array where key will be post id of an attachement
$mapImages = [];
foreach ($images as $image) {
$mapImages[$image->ID] = $image->guid;
}
Now we have all atachements but are missing all referenced images/files.
Lets continue by selecting all meta for our post (resort).
$metas = $wpdb->get_results("select meta_key,meta_value from wp_postmeta where post_id=" . $postId);
And index them by an meta key
$mapMetas = [];
foreach ($metas as $meta) {
$mapMetas[$meta->meta_key] = $meta->meta_value;
}
Lets say our post ($postId) has an 9 entries in 'resort_pics' with an image uploaded to its 'picture' field, then $mapMetas['resort_pics'] will have an value of 8.
Now the way how repeater fields keys are stored in $mapMetas array, is actually an :
'resort_pics_0_picture' -> itsPostId (5640 for example)
'resort_pics_1_picture' -> itsPostId (5641 for example)
'resort_pics_2_picture' -> itsPostId (5642 for example)
...
'resort_pics_8_picture' -> itsPostId (5648 for example)
Knowing this we can get simply all image urls for "resort_pics"
for ($i = 0; $i < $mapMetas['resort_pics']; $i++) {
$picture = [];
$picture['name'] = $mapMetas['resort_pics_' . $i . '_picture_title'];
$picture['url'] = $mapImages[$mapMetas['resort_pics_' . $i . '_picture']];
$pictures[] = $picture;
}
You may already get to this point, simply from $mapMetas get image ID and using it get an image url from $mapImages.
Lets say 'resort_pics_1_picture' is 'referenced' one (not directly uploaded image), we have its id '5641' but since its not connected to our $postID but to some other post id when it was actually uploaded. Its missing in our $mapImages array, so lets edit this code a bit.
for ($i = 0; $i < $mapMetas['resort_pics']; $i++) {
$picture = [];
$picture['name'] = $mapMetas['resort_pics_' . $i . '_picture_title'];
$picture['url'] = getAttachmentOrItsReferenceUrl('resort_pics_' . $i . '_picture', $mapImages, $mapMetas);
$pictures[] = $picture;
}
We have added an getAttachementOrItsReferenceUrl() method, which will simply first check if we already have this image (all uploaded to this post) and if not will fetch image data by its post id from 'wp_posts' table..
function getAttachmentOrItsReferenceUrl($code, $allAttachmentById, $allPostMetaByKey) {
global $wpdb;
$attachmentUrl = $allAttachmentById[$allPostMetaByKey[$code]];
if($attachmentUrl === null && isset($allPostMetaByKey[$code]) && $allPostMetaByKey[$code] !== '') {
$attachments = $wpdb->get_results("select ID,guid from wp_posts where ID = " . $allPostMetaByKey[$code]);
foreach ($attachments as $image) {
return $image->guid;
break;
}
} else {
return $attachmentUrl;
}
return "";
}
Finnal thoughts :
If you know your fields structure you can build up its key pretty straightforward
For an example
'rooms' repeater which has inside 'room_gallery' repeater which has inside 'image' image field.
'rooms_0_room_gallery_0_image'
--
$mapMetas['rooms'] - number of rooms
$mapMetas['rooms_' . $i . '_room_gallery'] - number of gallery images for room
--
'rooms_' . $i . '_room_gallery_' . $j . '_image'
How heavy is it ? Not really, if you are like me, having only small amount of referenced images you wont even feel it. All we added to load is an one meta query for an post, if no images are referenced that's all, then for every referenced image there is one more query, but its query on ID should be fast. There is a lot of way how to make load less, for example not do query for every single missing image, but do single query at the end with 'where in (id1,id2..)' to have single query to get all, or after fetching new image data, store it in some global array by its id, and check this array before fetching image for next posts (so if one image is stored in 200 posts, and you are fetching all it would make only 1 query), you got the point I leave it just at the ideas since this is bloody long post even without that :)
Hope this will help anybody in future.

Related

Custom Taxonomies and how to stay in them when the posts have multiple terms selected?

Wondering if anyone can help me think this one out?
Whilst in lock-down, I've been putting together a simple site to organise my collection of Retro Gaming Adverts covering systems from the Atari 2600 up to the N64. I've still got a few 1000 to add to the site (takes time) but i've come across an issue I'm not sure how to implement a fix for.
You can browse the adverts by system through their single post pages but if an advert covers multiple systems it messes up the previous and next posts link and will drop you into another system.
For Example: If you're using the next and previous post links to go through the "mega drive / genesis" section once you get to " Battletoads and Double Dragon " when you press the next post arrow this time you're suddenly going through adverts tagged as NES, due to the fact thats the first term associated with it.
See : https://www.retrogameads.com/system/mega-drive/ and click on the first advert, then keep pressing the next arrow and you'll see what i mean.
I guess I could post each advert multiple times for each system but I don't like the idea of that.
Anyone got any suggestions on how I could work out what Term the user was browsing and keep them in that one?
Bare in mind this site is a work in progress so the design is just something basic till i work out the best way to organise things.
Let me know your thoughts.
Update:
Current method for getting prev next posts...
<?php
$terms = get_the_terms( $post->ID, 'system' );
$i = 0;
$systems = array();
foreach ( $terms as $term ) {
$systems[$i] = $term->slug;
$i++;
}
$postlist_args = array(
'posts_per_page' => -1,
'post_type' => 'portfolio',
'system' => $systems[0],
'order' => 'ASC',
'orderby' => 'title'
);
$postlist = get_posts( $postlist_args );
$ids = array();
foreach ($postlist as $thepost) {
$ids[] = $thepost->ID;
}
$thisindex = array_search($post->ID, $ids);
$previd = $ids[$thisindex-1];
$nextid = $ids[$thisindex+1];
?>
<div class="prev_next">
<?php
if ( !empty($previd) ) {
echo '<div class="older"><a rel="prev" href="' . get_permalink($previd). '">‹</a></div>';
}
if ( !empty($nextid) ) {
echo '<div class="newer"><a rel="next" href="' . get_permalink($nextid). '">›</a></div>';
}
?>
When you click on an advert, you're essentially visiting the single page for that advert. At that moment, WP does not know/remember that the user only wants to see adverts from the system you clicked.
How are you rendering the previous/next links right now?
One possible solution could be to add a parameter to the URL and then take this into account in the PHP code when rendering the previous/next links. (/portfolio/advert-name/?system=mega-drive for example)
Edit: Of course the URL could also be made prettier... if you want to put in some extra work, you could register a permalink of the form /portfolio/mega-drive/advert-name/ for example. But this would require a bit more work.
Would that work? I think it would be the best solution considering the alternatives.
Update: For the actual implementation, the get_next_post_where and get_previous_post_where filters might prove to be very useful. You could make it so that it takes the system parameter into account for the previous/next links.
Another option: You could also set up a PHP session and remember the current system that way, but then you will require a PHP session, which is not a good thing, and it will also prevent you from using full page caching (performance optimization).
Yet another option would be to remember the current system client-side through a cookie. But in that case you have caching issues again unless you load the previous/next links through AJAX.
After reading the update on your question, I have the following notes:
system is not a valid argument and will be ignored on the get_posts() call.
the method you use to get the previous and next posts is very inefficient, because you query the whole database, and then you save everything in memory, and then you comb through the whole result set in memory, using a lot of unnecessary ram and CPU power
So how can we improve this?
Simple: Use the get_previous_post and get_next_post functions on the $post. It accepts three arguments. Here is the example for get_next_post (but get_previous_post is basically the same):
get_next_post( bool $in_same_term = false, array|string $excluded_terms = '', string $taxonomy = 'category' )
Now if you set $in_same_term to true then the next post will be of a post that shares at least one taxonomy term (system in our case).
You also have to set $taxonomy to system because that is the custom taxonomy.
And the other parameter is $excluded_terms. Too bad there is no $included_terms otherwise we could just put the system we want in there. But we can do it another way... We can filter out the current system (in the system GET parameter in our URL) and keep all other systems as systems to exclude.
So let's build what we need now.
global $post;
// What system did we come from?
$system = $_GET['system'] ?? null; // Set to null if nothing was specified (uses PHP's null coalescing operator available since PHP 7
// Exclude nothing by default
$excluded_term_ids = [];
// If we came here by clicking on a system, then exclude all other systems so the previous/next links will be of the same system only
if ($system) {
// Retrieve system terms for this post
$terms = get_the_terms( $post, 'system' );
// Filter the list of terms to remove the system we came from
// This way we can create a list of terms to exclude
$excluded_terms = array_filter( $terms, function ( $term ) use ( $system ) {
return $term->slug != $system;
} );
// The get_previous_post and get_next_post functions expect $excluded_terms to be an array of term IDs, so we must map the WP_Term objects into IDs
$excluded_term_ids = array_map( function ( $term ) {
return $term->term_id;
}, $excluded_terms );
}
// Retrieve previous and next post
$previous_post = $post->get_previous_post( true, $excluded_term_ids, 'system' );
$previous_post = $post->get_next_post( true, $excluded_term_ids, 'system' );
// Echo out the page links
// And don't forget to re-add the ?system= parameter to the URL
$url_suffix = $system ? ('?system=' . $system) : '';
if ( $previous_post ) {
echo '<div class="older"><a rel="prev" href="' . get_permalink($previous_post) . $url_suffix . '">‹</a></div>';
}
if ( $next_post ) {
echo '<div class="newer"><a rel="next" href="' . get_permalink($next_post) . $url_suffix . '">›</a></div>';
}
NOTE: Untested code.. So there might be a small bug somewhere.. Let me know if you encounter an issue with this code..
Important: On the page of a system, you must now also add '?system=current-system' to the URLs that you render.
Probably something like: echo get_permalink($advert) . '?system=' . $post->post_name (could be different depending on how your code is on that screen..)

Woocommerce Dynamic Pricing - manually inserting pricing rules

I am using the Woocommerce Dynamic Pricing plugin, which is very useful but does not easily allow me to ammend pricing updates via. the database.
Looking at the sample data,
{"set_5339c459a78e7":
{"conditions_type":"all",
"conditions":{"1":{"type":"apply_to","args":{"applies_to":"everyone"}}},
"collector":{"type":"product"},
"mode":"block",
"date_from":"",
"date_to":"",
"rules":{"1":{"from":"","to":"","type":"price_discount","amount":""}},
"blockrules": {"1":{
"from":"2",
"adjust":"1",
"type":"fixed_adjustment",
"amount":"0.26","repeating":"yes"}}}}
it seems that the meta requires set_* to be specific with the product meta, or it will not apply correctly.
Revising the code, I notice this:
$terms = get_terms('product_cat', array('hierarchical' => false, 'hide_empty' => false, 'parent' => 0));
foreach ($terms as $item_id => $item) {
$set_index = $item->term_id;
$name = 'set_' . $set_index;
}
This is bizarre to me, as the term_id appears to be a 13 character alphanumeric string than the expected bigint. Could anyone explain how I can reproduce this string for when I manually update my tables?
I had a look through the code and I found that in /admin/admin-init.php where it specifies the AJAX handlers, this is how it comes up with new set names:
function woocommerce_pricing_product_admin_create_empty_ruleset() {
global $wc_product_pricing_admin;
$wc_product_pricing_admin->create_empty_ruleset( uniqid('set_') );
die();
}
As you can see it just uses PHP's uniqid function prefixed by nothing but "set_" so in the case of product rules it appears to be just a random ID.
Hope that helps.

Wordpress Loops: Excluding by Tag String, Register by Function?

I have 3 loops running on the front page.
One for the slider, and it wants posts that have the tag "slider".
One for featured articles, and it wants posts that have the tag "featured".
And a third I am calling in loop_latest.php, it wants the 6 latest posts; the trick here is those need to be the 6 latests that do NOT have the tags "slider" or "featured".
So I have this query.
$query = new WP_Query(
array(
'showposts' => '6',
'tag_not_in' => array('featured, slider'),
) );
I'm pretty sure the problem here is that "tag_not_in" doesn't like strings, it wants IDs.
SO! Is there a way to pass it the strings?
If not, how do I divine what the IDs of tags are?
Can I run some code in "functions.php" to set and reserve the ids? featured == 777, slider == 888
Something like that?
I'd like to be able to SET them so that gets packaged with this theme. Rather than have to hope that when the client registers the tags "slider" and "featured" they match up with what I have chosen in the loops/query.
the correct parameter is tag__not_in (with 2 underscores).
additionally - to get your tag ID put this code in your functions.php
function get_tag_id_by_name($tag_name) {
global $wpdb;
$tag_ID = $wpdb->get_var("SELECT * FROM ".$wpdb->terms." WHERE `name` = '".$tag_name."'");
return $tag_ID;
}
and your new code should be:
$featuredtag = get_tag_id_by_name('featured');
$slidertag = get_tag_id_by_name('slider');
$query = new WP_Query(
array(
'showposts' => '6',
'tag__not_in' => array($featuredtag, $slidertag),
) );

WordPress: Having trouble in pagination for plugin settings page

Developing a plugin in WordPress and getting well but stuck on pagination for the plugin page. Here is my code downloaded from internet ( got reference from here )
$items = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->review_media GROUP BY post_id")); // number of total rows in the database
// tested and got results as commented
print_r($items); // say this is outputs value 2
echo $rm_options['list_per_page']; // this is my option set with value 1
if($items > 0) {
$p = new pagination;
$p->items($items);
$p->limit(empty($rm_options['list_per_page']) ? 20 : $rm_options['list_per_page']); // Limit entries per page
$p->target("admin.php?page=moderate.php");
$p->currentPage($_GET[$p->paging]); // Gets and validates the current page
$p->calculate(); // Calculates what to show
$p->parameterName('paging');
$p->adjacents(1); //No. of page away from the current page
if(!isset($_GET['paging'])) {
$p->page = 1;
} else {
$p->page = $_GET['paging'];
}
//Query for limit paging
$limit = "LIMIT " . ($p->page - 1) * $p->limit . ", " . $p->limit;
} else {
echo "No Record Found";
}
When I don't group my query by post_id it is working fine but as soon as I grouped its behaving weird. It is creating a pagination links and getting blank page. I think the reason is grouping the row. But don't know how to solve this.
Here is my table screenshot
Thanks a lot for your help...
If you use WordPress WP_List_Table class, it will take care of the pagination and provide a default table experience for the user.
This tutorial covers it all, the pagination part is:
function prepare_items() {
[...]
$per_page = 5;
$current_page = $this->get_pagenum();
$total_items = count($this->example_data);
// only necessary because we have sample data
$this->found_data = array_slice($this->example_data,(($current_page-1)*$per_page),$per_page);
$this->set_pagination_args( array(
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page //WE have to determine how many items to show on a page
) );
$this->items = $this->found_data;
}
And here's the full plugin shown in the tutorial. And in this other plugin you can see WP_List_Table in action using database data.

WP Settings API save to multiple options

In the Wordpress Settings API, creating a new options page usually starts out with
register_setting('sample_options', 'my_option');
add_settings_section('section', 'Sample Options', 'callback1', 'page');
add_settings_field('name', 'Label', 'callback2', 'page', 'section');
In this simplified example, the data gets saved in the option my_option making the value of name accessible through
$option = get_option('my_option');
$name = $option['name']; // Got it
But what if the value of the name field is there not to place a new value but to update an already existing option that's not my_option like for example this_other_option? I guess what I'm really looking for is is it possible for one field to save to multiple options (my_option and this_other_option) while using the Settings API?
I suppose you could use a callback in register_setting. It would look something like the following:
<?php
register_setting('sample_options', 'my_option', 'my_sanitize_callback');
function my_sanitize_callback($value, $option) {
$value = mysql_real_escape_string($value);
update_option('my_other_option', $value);
return $value;
}
?>
You may have to tweak that a bit. I haven't tested it.

Resources