wordpress count image attachments - wordpress

I'm looking for some help, for some reason this code isn't working when trying to display total image attachments on the main index.php page.
// Get all the attachments
$attachments = get_posts ( array(
'numberposts' => -1,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
) );
// Count all the attachments
$total = count( $attachments );
The problem is, the loop is in the main index.php page, but it's calling a post.php template so I have placed this code there instead (I'm assuming that's still in the loop?) I am then calling $total just below it where I want to show "View all # images".
Any ideas why this is just displaying the number as 0 even though I have added an image gallery to the post using the basic Wordpress gallery media library?
Thanks

The attachment count only increases if it's attached to a post. You can force the count by adding this:
$wp_taxonomies['category']->update_count_callback = '_update_generic_term_count';
in a function in your functions.php something like this:
function change_category_arg() {
global $wp_taxonomies;
if ( ! taxonomy_exists('category') )
return false;
$wp_taxonomies['category']->update_count_callback = '_update_generic_term_count';
}
add_action( 'init', 'change_category_arg' );
Explanation:
This is significant in the case of attachments. Because an attachment
is a type of post, the default _update_post_term_count() will be used.
However, this may be undesirable, because this will only count
attachments that are actually attached to another post (like when you
insert an image into a post). This means that attachments that you
simply upload to WordPress using the Media Library, but do not
actually attach to another post will not be counted. If your intention
behind associating a taxonomy with attachments was to leverage the
Media Library as a sort of Document Management solution, you are
probably more interested in the counts of unattached Media items, than
in those attached to posts. In this case, you should force the use of
_update_generic_term_count() by setting '_update_generic_term_count' as the value for update_count_callback.
from Wordpress Codex on register_taxonomy

Related

How to handle/manage custom images?

I am working on a special plugin for a customer.
The situation in short:
The plugin contains a automatic import for a .zip file. Inside this files are one .xml file and images.
The plugin reads the .xml file and insert the information to the database.
My question:
How I can handle the images the best way. Should I import them into the wordpress gallery or should I manage them on my own.
Is there a way to use the wordpress gallery, because it will automatic generate thumbnails, or is it not a good idea?
I need some suggestions. Thanks!
You should add images in wordpress gallery. Then you have to get these uploaded images from the wordpress gallery:
Step 1: Prepare the query
global $post;
$args = array(
'post_parent' => $post->ID, // For the current post
'post_type' => 'attachment', // Get all post attachments
'post_mime_type' => 'image', // Only grab images
'order' => 'ASC', // List in ascending order
'orderby' => 'menu_order', // List them in their menu order
'numberposts' => -1, // Show all attachments
'post_status' => null, // For any post status
);
First, we set up the global Post variable ($post) so we can have access to the relevant data about our post.
Second, we set up an array of arguments ($args) that define the kind of information we want to retrieve. Specifically, we need to get images that are attached to the current post. We're also going to get all of them, and return them in the same order they appear in the WordPress gallery.
Step 2: Retrieve the Images from Wordpress gallery
// Retrieve the items that match our query; in this case, images attached to the current post.
$attachments = get_posts($args);
// If any images are attached to the current post, do the following:
if ($attachments) {
// Initialize a counter so we can keep track of which image we are on.
$count = 0;
// Now we loop through all of the images that we found
foreach ($attachments as $attachment) {
Here we are using the WordPress get_posts function to retrieve the images that match our criteria as defined in $args. We are then storing the results in a variable called $attachments.
Next, we check to see if $attachments exists. If this variable is empty (as will be the case when your post or page has no images attached to it), then no further code will execute. If $attachments does have content, then we move on to the next step.
Set parameters for a WordPress function called wp_get_attachment_image for the images information.
Source: Read the link for complete tutorial or other steps > https://code.tutsplus.com/tutorials/how-to-create-an-instant-image-gallery-plugin-for-wordpress--wp-25321

Order or orderby not working in WP_Query when you are in category page

I have the next WP_Query in footer.php in my wordpress:
wp_reset_postdata();
$argsLast = array(
'post_type' => 'post',
'posts_per_page' => 3,
'orderby' => 'date',
'order' => 'DESC',
'category__not_in' => array(193,189,192,195,207,190,213),
);
$ultimosposts = new WP_Query( $argsLast );
And it works fine in all pages of my wordpress except the category pages.
I have done several tests and the paremeter which doesn't work are 'order' or 'orderby'.
I would be grateful if someone could explain what is going on.
SOLVED: The problem was caused by a plugin: Sort Categories By Title
I deactivated the plugin and I'm sorting the posts in category using the next code in functions.php of my theme (a lot of thanks to #PieterGoosen, now I understand much better the queries in Wordpress):
add_action( 'pre_get_posts', 'orden_posts_categoria');
function orden_posts_categoria($q){
if (!is_admin()
&& $q->is_main_query()
&& $q->is_category()
) {
$q->set( 'orderby', 'title' );
$q->set( 'order', 'ASC' );
}
}
Note: this code is from #PieterGoosen
In this way, I modify the main query of wordpress. So it is very important setting the correct conditions in the selective structure.
Glad you have deactivated the plugin as in my opinion, the plugin is a pile off crap due to the fact that it breaks page functionalities. I can only speculate, but it either uses pre_get_posts wrongly or it uses query_posts which you should never ever use.
To solve your issue, you need to go back to the dafault loop which should look like this
if ( have_posts() ) { // Sometimes category pages don't have this, not really necessary
while ( have_posts() ) {
the_post();
// Your markup and template tags
}
}
You again should see posts on your category page ordered by date as per default.
Now, to solve the issue of sorting your posts by title on category pages, we will use pre_get_posts to alter the main query variables before the main query run. This is the recommended method, you should never replace the main query with a custom one to solve these kind of issues. It leads to other issues, specially wrong posts and wrong pagination
In your functions.php or your own custom plugin, add the following
add_action( 'pre_get_posts', function ($q )
{
if ( !is_admin() // Check that we are on the front end and not back end
&& $q->is_main_query() // Make sure we only alter the main query
&& $q->is_category() // Only target category pages
) {
$q->set( 'orderby', 'title' );
$q->set( 'order', 'ASC' );
}
});
The check I have done is very very important. pre_get_posts alters all instances of WP_Query, not only the main query, and this happens back end and front end and on all pages. Always make sure that you use these checks when using pre_get_posts
You should now have your category pages sorted by post title, and your custom query 8n the footer should also now correctly on category pages.
Just one last tip, to avoid custom filters altering your custom WP_Query instances, use 'suppress_filters' => true in your query arguments. get_posts does the same to avoid custom filters altering the output
EDIT
Just on the issue of queries, you should take your time and read this post I have done on the subject of the main query and custom queries

How to get Wordpress attachments to work for existing images inside the Media Library?

I want to display the images from each Wordpress post on a separate page.
When using get_children (or get_posts) the 'post_type' => 'attachment' only works if I've just uploaded an image (via WP's 'ADD MEDIA > UPLOAD FILES') to that particular post.
It does not work if I add an existing image to a post that's already in my WP MEDIA LIBRARY).
Is there anyway for 'attachment' to work for existing (already uploaded) images?
See my test function:
function echo_first_image($postID){
$args = array(
'post_type' => 'attachment',
'post_parent' => $postID
);
$attachments = get_children( $args );
if($attachments){
echo'YES'; // test answer
}else{
echo'NO'; // test answer
}
}
EDIT: each 'post_type' that is an 'attachment' has a single 'post_parent' - does this mean an attachment can ONLY have a single parent?
Currently as of writing, Wordpress 4.1 does not include multi-parent attachments because the database relationship is one-to-one, not one-to-many. You would have to find a plugin, or write your own to get around that.

Wordpress query from Magento/WHMCS return wrong result

I am trying to display posts from a specific cateogry in WordPress in a footer column on a site. It works fine unless the footer is displaying on a page that is integrated in either WHMCS or Magento. For some reason, on those pages within those apps, it still displays the blog post column, but instead of returning the last X # of posts in the specified category, it seems to return the last post X # of times.
For example, here is the stand alone Wordpress blog column pulling from a specific category:
http://www.thinkshovels.com/includes/latest_work.php
This is exactly what we want shown throughout the site, however if you visit http://www.thinkshovels.com/service/ you can see that the middle column is not displaying that info.
Here is the code querying wordpress:
define('WP_USE_THEMES', false);
require('/home/shovels/public_html/blog/wp-load.php');
$qarray = array('cat' => '5', 'posts_per_page' => 4);
query_posts($qarray);
while (have_posts()): the_post();
$args = array( 'post_type' => 'attachment', 'numberposts' => -1,
'post_status' => null, 'post_parent' => $post->ID );
I'm not sure if I have done something wrong here, or if there is a better way to approach this, but it seems that WHMCS and Magento break something with these queries.
Any tips/advice appreciated! Thanks.
Instead of query_posts try to use get_posts instead.
According to the article from Developer.WordPress.com you should avoid using query_posts.

Wordpress get_posts (show all attachments) pagination outside of the loop

On one of my Wordpress pages (which is really an image blog site) I'm using masonry.js with the Wordpress function get_posts to dump all attachments to my blog posts and display them in a grid. This works fine. However, there's obviously a lot of images and I was hoping to use the infinitescroll.js with this. The only problem is that the get_posts function, outside the loop, doesn't retain the pagination and therefore the functionality of infinitescroll.js doesn't work.
Here is the code I am using to dump all the attachments:
<?php
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => null );
$attachments = get_posts( $args );
if ($attachments) {
foreach ( $attachments as $post ) {
setup_postdata($post);
the_attachment_link($post->ID, true);
the_excerpt();
}
}
?>
Is there anyway of adding in pagination to the original Wordpress get_posts() attachment dump outside of the loop, or can anyone think of a solution?
I've done something similar using the 'offset' parameter for get posts.
Basically with each new call to get posts, simply increase your offset amount by the amount of new thumbnails you want to display each time. When the number of thumbnails returned is less than your offset amount, you have reached the end of your posts.
Another solution is to use the pagination parameters of the Wp_Query class. See here for what these are.

Resources