Get attachment ID - php

How do i get the "attachement_id="
like here ;
I hope someone can give me an answer. I want to tie this id to a jquery selector for fullscreen images.

It is a little bit complicated, because all attachments are linked to the given posts.
Example: To display all of the images and titles attached to a certain page and display them as a list you can use the following:
<?php if ( have_posts() ) : while ( have_posts() ) : the_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 ) {
echo wp_get_attachment_image( $attachment->ID, 'full' );
echo '<br/>';
echo apply_filters( 'the_title', $attachment->post_title );
}
}
endwhile; endif; ?>

Fixed it this way;
foreach ($metas as $metakey) {
$image_id++;
echo "<div class='image' id='img_$image_id'>";
and for the jquery selector;
$('#img\\_<?php echo $image_id ?>').on('click', function () {
this way each image i click, actually is that image. So i got this
$full_image = wp_get_attachment_image_src($metakey['image'], 'full');
<script>
$('#img\\_<?php echo $image_id ?>').on('click', function () {
alert('<?php echo $full_image[0] ?>');
});
</script>
This results that each image i click i get the right url.
Thanks though.

What you looking for is :
$attachment->ID
Take a look at the function wp_get_attachment_image
Reference: Wordpress Attachment
You have to get the $post->ID in order for that to work.
Reference : https://core.trac.wordpress.org/browser/tags/4.0.1/src/wp-includes/link-template.php#L392

Related

WooCommerce display product thumbnail and add to cart button

I have created a live search field that fetches the title of the product using AJAX.
It works correctly, however, I would like to fetch the product thumbnail and the ‘Add to the cart’ button.
**Edit: I have added the output for the thumbnail and add to cart button. It works, but it only displays in singular rows. How can I update my output in rows of 4 as below?
Front End Code
<input type="text" name="keyword" id="keyword" onkeyup="fetch()">
<div id="datafetch">Your numbers will show here</div>
<script>
function fetch(){
$.post('<?php echo admin_url('admin-ajax.php'); ?>',{'action':'my_action'},
function(response){
$('#datafetch').append(response);
console.log(result);
});
}
</script>
Code in Functions.php
<?php
}// LOTTERY start the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
global $product;
$product = get_product( get_the_ID() ); //set the global product object
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
<h4><?php the_title();?></h4>
<h4><?php the_post_thumbnail();?></h4>
<p><?php echo $product->get_price_html(); ?></p>
<?php woocommerce_template_loop_add_to_cart(); //ouptput the woocommerce loop add to cart button ?>
<?php
}
endwhile;
wp_reset_postdata();
endif;
die();
}
You can use this get_the_post_thumbnail_url(get_the_ID()) to get thumbnail URL and add image.
You can use this https://yourdomain.com/?add-to-cart=<product_id> to add product add to cart URL.
https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/
Try this approach
//Ajax
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {
//get image and add-to-cart buttom here
$query->the_post();
global $product;
wc_get_template_part('content', 'product');
//End get image and add-to-cart buttom here
}
endwhile;
wp_reset_postdata();
endif;
die();
}

wordpress shortcode render content in dashboard also

I am using a simple wordpress shortcode
function my_recent_post()
{
echo 'hello';
}
add_shortcode( 'recent', 'my_recent_post' );
with the shortcode [recent] and its working fine and visible in front page,
but the problem is, its printing the hello in the dashboard also.
below is the screenshot, can anyone please help.
Update:
I was actually trying to show posts, so can you help me with this, because it renders the lists of posts in the dashboard itself like the "hello". I tried:
function lorem_function() {
global $post;
$args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ( $postslist as $post ) :
setup_postdata( $post ); ?>
<div>
<?php the_date(); ?> <br /> <?php the_title(); ?> <?php the_excerpt(); ?>
</div>
<?php endforeach;
wp_reset_postdata();
return;
}
add_shortcode('lorem', 'lorem_function');
Based on your comments to me & Nikita Dudarev, what you need to do is create a variable to hold all the post information and then return it. Using the function you posted as an example:
function lorem_function() {
global $post;
$args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
// create a variable to hold the post information
$html ="";
foreach ( $postslist as $post ) :
setup_postdata( $post );
$backgroundstyle = "";
// get the featured image and set it as the background
if ( has_post_thumbnail() ) { // make sure the post has a featured image
$imageurl = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium' ); // you can change "medium" to "thumbnail or full depending on the size you need
// add the css for the background image. You can include background-size etc ad required
$backgroundstyle = "background-image: url('".$imageurl[0]."');";
}
// add the information to the variable
$html .= '<div style="'.$backgroundstyle.'">';
$html .= get_the_date();
$html .= "<br />";
$html .= get_the_title();
$html .= get_the_excerpt();
$html .= "</div>";
endforeach;
wp_reset_postdata();
return $html;
}
add_shortcode('lorem', 'lorem_function');
Note that the_date(), the_title() and the_excerpt() all display the information (just like echo).
Instead you must use get_the_date(), get_the_title() and get_the_excerpt() - these get the same information, but instead of displaying it directly, they return it as a variable which you can then store in your html string to be returned.
Update:
As you don't want to use the variable name on each line for whatever reason, you can do it like this:
$html .= "<div>".get_the_date()."<br />".get_the_title().get_the_excerpt()."</div>";
I'm not sure why you specifically want to change it to do that - it makes absolutely no difference to how it works, it just makes it harder to read and identify any errors :-)
Your function must return a value, not output
function my_recent_post()
{
return 'hello';
}
add_shortcode( 'recent', 'my_recent_post' );

Post image only with a e keyword

I want to post a gallery formed by a number of images from my site that have a certain keyword. Like from a certain location, or time. I thought to use the caption option or the description option from wordpress. Images will have more keywords, something like: "Location" "Sunset". I tryed to use this What is the function got get all the media files wordpress? combined with https://wordpress.org/ideas/topic/functions-to-get-an-attachments-caption-title-alt-description but I cant get them working. Can you help me please. But I am a newbie so can you explain exactly what to write in function.php and what to write in page-name.php
LE: <?php $attachment_meta = wp_get_attachment(wp_get_attachement_id()); ?>
<?php if ($attachement_meta[caption] == 'Ceahlau' ) ?>
echo do_shortcode('[gallery columns="4" link="file" ids=" <?php wp_get_attachement_id() ?>"]')
<?php else: ?>
<?php endif; ?>
This is what I have now in my page-name.php
<?php $attachment_meta = wp_get_attachment(wp_get_attachement_id()); ?>
<?php if ($attachement_meta[caption] == 'Ceahlau' ) ?>
echo do_shortcode('[gallery columns="4" link="file" ids=" <?php
wp_get_attachement_id() ?>"]')
<?php else: ?>
<?php endif; ?>'
This is what i have now in my page-name.php
This is what i have now in my page-name.php
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => null, // any parent
'post_mime_type' => 'image'
);
$attachments = get_posts($args);
if ($attachments) {
$attachment_meta = wp_get_attachment($attachment->ID);
foreach ($attachments as $post) {
if ($attachment_meta['caption'] == 'Ceahlau' ){
setup_postdata($post);
echo wp_get_attachment_image( $attachment->ID, 'full' );
the_attachment_link($post->ID, false);
}
}
}
?>

Custom wordpress function to display related posts based on multiple tags

I'm building a wordpress site and want to show related posts based on tags when viewing a single post. Currently I'm using the below function to do this and it works.
My issue is that I want to prioritise related posts that have the most tags in common. Usually I have 3-5 tags for each posts so I want to display posts with 3 tags in common before 1 tag for example. I've tried some different code snippets that should be able to do this but I haven't managed to get it to work so far.
Any help will be appreciated, thanks.
function smak_related_posts() {
global $post;
$tags = wp_get_post_tags( $post->ID );
if($tags) {
foreach( $tags as $tag ) {
$tag_arr .= $tag->slug . ',';
}
$args = array(
'tag' => $tag_arr,
'numberposts' => 4,
'post__not_in' => array($post->ID),
'post_type' => array('post', 'projects'),
);
$related_posts = get_posts( $args );
if($related_posts) {
echo '<footer class="entry-footer">';
echo '<h3>Se også...</h3>';
echo '<div id="masonry-loop">';
get_template_part( 'template-parts/content', 'masonry_sizer' );
foreach ( $related_posts as $post ) : setup_postdata( $post );
get_template_part( 'template-parts/content', 'masonry' );
endforeach; }
}
echo '</div>';
echo '</div>';
wp_reset_postdata();
}

Wordpress Custom fields display file URL

I have the following code and need to show THREE things from my custom post type called fact-sheet.
The Title
The summary (fact_sheet_summary)
A file upload URL (fact_sheet_pdf_link)
I can get the first two to work but no idea how to do the third.
Basically my output should be...
The Title
The Summary paragraph
Click here to download as PDF
Any ideas how I can query to list all of these post type results? Is there a better way to do this rather than what I have below? The main problem is, I can't get the URL of the uploaded file.
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'fact-sheet',
'order' => 'ASC',
));
if($posts)
{
foreach($posts as $post)
{
echo '<span class="fact-sheet-title">' . get_the_title($post->ID) . '</span><br />';
echo '<p><span class="fact-sheet-summary">' . the_field('fact_sheet_summary') . '</span></p>';
}
}
?>
I think It's better to use query_posts() as you can use The Loop default structure.
As for the custom fields (Using ACF Plugin), you're using the_field(), which automatically echoes the retrieved field value. You can use, in other hand, the get_field() function, which just returns the value of the field.
You could do something like this:
// Query all posts from 'fact-sheet' post_type
query_posts(array(
'numberposts' => -1,
'post_type' => 'fact-sheet',
'order' => 'ASC',
// Getting all posts, limitless
'posts_per_page' => -1,
));
// Loop throught them
while(have_posts()){
the_post();
echo '<span class="fact-sheet-title">' . get_the_title() . '</span><br />';
echo '<p><span class="fact-sheet-summary">' . get_field('fact_sheet_summary') . '</span></p>';
// Echos the link to PDF Download
echo '<p>Click here to download as PDF</p>';
}
// Once you're done, you reset the Default WP Query
wp_reset_query();
In case you might need further explanation about wp_reset_query(), check this out.
Can you try this? It's slightly modified from the manual of the WP Codex (not much)
<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$args = array(
'post_type' => 'attachment',
'post_mime_type' => array('application/pdf'),
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li>';
the_attachment_link( $attachment->ID, true );
echo '<p>';
echo apply_filters( 'the_title', $attachment->post_title );
echo '</p></li>';
}
}
endwhile; endif; ?>
</ul>
If it works, maybe it's better to modify a working sample to your needs - by adding your custom fields. Just my thoughts :-)

Categories