Display a random post attachment on homepage in Wordpress - image

I'm trying to get 1 random image attached to a post, and display it on the front page (changing which image is displayed on refresh). All the code I've seen is showing how to display an attachment from within the loop on the post page, but this will be getting the attachment from one page and displaying it on a different page.
Any help would be huge as I don't really have a starting point on this.

You can use WP_Query to query attachments directly. They is actually a post type just for attachments. This bit of code will spit out the <img> tag for a random image:
$query = new WP_Query( array( 'post_status' => 'any', 'post_type' => 'attachment' ) );
$key = array_rand($query->posts, 1);
echo wp_get_attachment_image($query->posts[$key]->ID, 'medium');
The string medium can be replaced with another size you set in the media section of the dashboard, or a custom size you set in the code using add_image_size().

Untested, but this should grab only one row from your database, and it makes full use of the WP_Query functions.
You can change the size of the image that is displayed by replacing 'full' with an array (e.g. array(200, 130)). Check the codex for wp_get_attachment_image() for more informaion.
$args = array(
'orderby' => 'rand',
'post_type' => 'attachment'
'post_status' => 'inherit',
'posts_per_page' => 1
)
$query = new WP_Query($args);
if($query->have_posts()) : while($query->have_posts() : $query->the_post();
echo wp_get_attachment_image(get_the_ID(), 'full');
endwhile;
wp_reset_postdata();
endif;

Related

Woocommerce Filter Product by Attribute

I've been searching for many blogs and forum but this seems not yet answered yet. So i am trying to find a way how to filter product by attribute. I am using ajax to pull data and append it.The question is what will be the query to make a loop depend on what attribute.
Example.
Product A has Color:Blue,Red,Green and has a brand : BrandA , BrandB Product B has Color:Pink,Red,black.
All i want is to get all product with an attribute of Color [red and green] and Brand [BrandA] in a single query without using any plugin.
Here my code in my functions.php
function advanced_search(){
$html = "";
$args = array( 'post_type' => 'product','product_cat' => 'yarn');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ){
$loop->the_post();
ob_start();
get_template_part( 'templates/part', 'search-result' );
$html = ob_get_contents();
ob_end_clean();
}
wp_send_json(array( "product_id" => $product_id , "html" => $html ));
}
add_action('wp_ajax_get_advanced_search', 'advanced_search');
add_action('wp_ajax_nopriv_get_advanced_search', 'advanced_search');
I dont know where should i put the product attributes in my query. I hope anyone found an answer for this.Thank you very much.
You should be able to achieve what you're looking to do by using a tax_query combined with your WP_Query. Attached is a small example using a 'Brand' attribute and the 'EVGA' term inside it (which WooCommerce will turn into 'pa_brand' - product attribute brand).
$query = new WP_Query( array(
'tax_query' => array(
'relation'=>'AND',
array(
'taxonomy' => 'pa_brand',
'field' => 'slug',
'terms' => 'evga'
)
)
) );
You can find some more documentation on the above links to string a few tax queries together for additional filtering and functionality.

getData doesn't work, returns empty

I create my custom attribute, but when I go show this with my method it doesn't work!
See was do... create my attribute..
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$config = array(
'position' => 1,
'required'=> 0,
'label' => 'Height',
'type' => 'int',
'input' => 'text',
'apply_to' => 'simple,bundle,grouped,configurable'
);
$setup->addAttribute('catalog_product', 'height' , $config);
and I get a list of items in checkout...
$items = Mage::getModel('checkout/cart')->getQuote()->getAllVisibleItems();
foreach($items as $item){
echo $item->getSku() .'<br/>'; //just test... and all right!
echo $item->getHeight() .'<br/>'; //return empty! or....
echo $item->getData('height') .'<br/>';//return empty!
}
I set values in this attribute's fiels in my backend.
Thanks for help me!
Your attributes probably aren't being loaded by default. A cheat, without fixing the root problem of adding height to the collection's addAttributeToSelect() statement would be to load the product model again:
$product = Mage::getModel('catalog/product')->load($item->getProduct()->getId());
echo $product->getHeight();
This doesn't solve the root of the problem though, and fires off an additional database query.
I asked a similar question a couple of months ago regarding loading additional data which contains some more information, although more related to collection loading than individual models: Retrieving additional data from already loaded Magento models.
Try echo $item->getProduct()->getHeight();

Wordpress - changing attributes of featured images

I want to use Featured Images (thumbnails) in my posts.
The thing is, I want to be able to change the following image attributes after the image has been attached to the post, but before the post has been published:
Title
Alternate Text
Caption
Description
How do you do that?
<?php
$size = array(150,150);
$default_attr = array(
'src' => $src,
'class' => "attachment-$size",
'alt' => trim(strip_tags( wp_postmeta->_wp_attachment_image_alt )),
'title' => trim(strip_tags( $attachment->post_title )),
);
the_post_thumbnail( $size, $attr );
?>
I'm still not clear what you're trying to do.
This will display the featured image in your markup using the post title as alt and title attributes.
$image_meta = wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium');
// replace 'medium' with 'thumbnail', 'large', or 'full'.
echo '<img src="'.$image_meta[0].'" alt="'.$post->post_title.'" title="'.$post->post_title.'" width="'.$image_meta[1].'" height="'.$image_meta[2].'"/>';
If you want to actually change the featured image title, alt, caption, description etc in the database, then you could look at the post_publish hook. This should get you started:
function do_stuff($post_ID){
global $post;
$post_thumbnail_id = get_post_thumbnail_id($post_ID);
if ($post_thumbnail_id){
// Do Stuff with your featured image id - $post_thumbnail_id
}
return $post_ID;
}
add_action('publish_post', 'do_stuff');
try this and its work fine.
$title_attribute = the_title_attribute( array( 'echo' => FALSE ) );
the_post_thumbnail(
'full',
array(
'alt' => $title_attribute,
'title' => $title_attribute
)
);

How to get and set image attachment metadata in wordpress?

I have post in WP. This post has attached image as attachment. I set description of this image via dialog (gallery tab) in post edit section.
Now I need WP functions to programmatically get all metadata for this attachment (description,title,caption,...) and another function to set the same data.
What functions to use ?
use get_children() to retrive atachement for posts.
$args = array(
'numberposts' => -1,
'order'=> 'ASC',
'post_mime_type' => 'image',
'post_parent' => $post->ID,
'post_status' => null,
'post_type' => 'attachment'
);
$attachments = get_children( $args );
a full example here Get URLs, Captions & Titles for Images Attached to Posts in WordPress
This works for me:
<?php
foreach ( $attachments as $attachment_id => $attachment ) {
$src = wp_get_attachment_image_src( $attachment_id, 'full' );
var_dump($src);
} ?>
array
0 => string 'http://example.com/wp-content/uploads/2009/08/DSC00261.JPG' (length=63)
1 => int 1632
2 => int 1224
3 => boolean false
The order of the array is allocated as follows.
$src[0] => url
$src[1] => width
$src[2] => height
$src[3] => icon

How can I import images as a HTML list in Wordpress?

My question is very simple: Is it possible to import many images at once in a post (such as the gallery does) but inside a <ul> for instance ?
The gallery import is, I think, the only way to import a group of images inside a post, but I can't handle the HTML in this case.
I can be wrong, but I didn't find anything about that. Thank you for your help.
You can insert your images in the gallery without importing it into your post. Then, in the single post template, you can query the images attached to the post to display them.
Attachments are just posts attached to a post, so let’s use get_posts():
function get_post_images($post) {
$args = array(
'post_type' => 'attachment', // Images attached to the post
'numberposts' => -1, // Get all attachments
'post_status' => null, // I don’t care about status for gallery images
'post_parent' => $post->ID, // The parent post
'exclude' => get_post_thumbnail_id($post->ID), // Exclude the thumbnail if you want it on your article list but not inside an article
'post_mime_type' => 'image', // The attachment type
'order' => 'ASC',
'orderby' => 'menu_order ID', // Order by menu_order then by ID
);
return get_posts($args);
}
I suggest to place this function in the functions.php file.
In your single.php file:
<ul>
<?php
$images = get_post_images($post);
foreach ($images as $image):
?>
<li><?php echo wp_get_attachment_image($image->ID, 'medium'); ?></li>
<?php endforeach; ?>
</ul>
WP Codex links:
get_posts()
Query parameters

Resources