I am trying to make the theme I am using (DICE) into pulling through title text of images.
The code I am using is below;
if ( has_post_thumbnail() ) {
if ( $linking == 'lightbox' ) {
$alt = esc_attr(get_the_title( $post->ID ) );
$the_title = esc_attr(get_the_title( $post->ID ) );
$img = get_the_post_thumbnail( $post->ID, $size, array( 'alt' => $alt, 'title' => $the_title ) );
}
else
$img = get_the_post_thumbnail( $post->ID, $size );
}
elseif( $placeholder ) {
$img = btp_render_placeholder( $size, '', false );
}
else {
return;
}
The only line I have added is
$the_title = esc_attr(get_the_title( $post->ID ) );
with
'title' => $the_title
in the array aswell. The alt text is pulling through fine, so I'm unsure as to why the title text isn't pulling through?
Any help is appreciated. Thanks.
Using two separate variables to get the same information is bad programming practice.
Try to use only one variable, like this:
if ( $linking == 'lightbox' ) {
$post_title = esc_attr(get_the_title( $post->ID ) );
//The Image
$img = get_the_post_thumbnail( $post->ID, $size, array( 'alt' => $post_title, 'title' => $post_title ) );
}
Related
So I'm using wordpress and ACF. I created a CPT called products and a custom taxonomy named product_types. I have a loop that displays all product_type sections and each section contains products tied to it. So I'm looking for ways to easily filter new products or popular products thats why I come up with adding a dedicated category for it but I dont want it to exclude it from my post loop. pls see img attached
enter image description here
Here's the code I'm working with atm
<?php
$cpt_name = 'products';
$taxonomy_name = 'product_type';
// Retrieve the terms in the above taxonomy.
$terms = get_terms( $taxonomy_name );
if ( empty( $terms ) || is_wp_error( $terms ) ) {
return;
}
echo '<div class="products-group">';
foreach( $terms as $term ) {
echo '<div class="products-category">';
echo '<h2 class="title-category">' . $term->name . '</h2>';
$args = array(
'post_type' => $cpt_name,
'tax_query' => array(
array(
'taxonomy' => $taxonomy_name,
'field' => 'slug',
'terms' => array( $term->slug ),
),
),
'posts_per_page' => -1,
'category__not_in' => array( 30 ),
);
$query = new WP_Query( $args );
echo '<div class="products-list">';
while ( $query->have_posts() ) {
$query->the_post();
$attachment_id = get_field('header_bg_image');
$size = "wide-thumbnail"; // (thumbnail, medium, large, full or custom size)
$image = wp_get_attachment_image_src( $attachment_id, $size );
if ( ! empty( $image ) ) {
$image_html = esc_url( $image[0] );
} else {
$image_html = 'https://rasons.ltd/wp-content/uploads/2020/02/interior-exterior-finish-800x400.jpg';
}
printf( '%s', get_the_permalink(), esc_attr( the_title_attribute( 'echo=0' ) ), get_the_title() );
}
echo '</ul>';
wp_reset_query();
echo '</div></div>';
} // end foreach.
echo '</div>';
?>
I would like to display one image at a time on my page, that is picked randomly from the images loaded in this page (from wordpress admin).
I am working with my own theme and I have a "front-page.php" file where I have my function to load the content of my page.
I don't know how to add the random image function to this code.
my PHP code:
<?php get_header(); ?>
<div class="container">
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
$images = [];
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
$image_url = ( !empty( wp_get_attachment_url( $attachment->ID ) ) ) ? wp_get_attachment_url( $attachment->ID ) : '';
$image_alt = ( !empty( get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true) ) ) ? get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true) : '';
$images[] = array(
'url' => $image_url,
'alt' => $image_alt
);
}
}
$image = $images[array_rand( $images, 1 )];
?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php
}
}
?>
</div>
Create an array of available images and then choose one at random.
$images = array(
'http://via.placeholder.com/350x150',
'http://via.placeholder.com/350x150',
'http://via.placeholder.com/350x150',
'http://via.placeholder.com/350x150',
);
$image_url = $images[array_rand( $images, 1 )];
echo $image_url;
If you want to include alt text, use a multidimensional array:
$images = array(
array( 'url' => 'http://via.placeholder.com/350x150', 'alt' => 'My image'),
array( 'url' => 'http://via.placeholder.com/350x150', 'alt' => 'My image'),
array( 'url' => 'http://via.placeholder.com/350x150', 'alt' => 'My image'),
array( 'url' => 'http://via.placeholder.com/350x150', 'alt' => 'My image'),
);
$image = $images[array_rand( $images, 1 )];
echo $image['url'];
echo $image['alt'];
From your response it sounds like you're trying to pull the images from the post content, if so, you'll need to loop through the post's attachments to create the images array. However, there are a number of potential pitfalls with this method. If I were you, I would create a gallery field using Advanced Custom Fields and use that as the source of the image group.
<?php
if ( have_posts() ) {
$images = [];
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 ) {
// get url from Plugin: WP Gallery Custom Links
$image_href = ( !empty( get_post_meta( $attachment->ID, '_gallery_link_url', true) ) ) ? get_post_meta( $attachment->ID, '_gallery_link_url', true) : '';
// get attachment
$image_url = ( !empty( wp_get_attachment_url( $attachment->ID ) ) ) ? wp_get_attachment_url( $attachment->ID ) : '';
$image_alt = ( !empty( get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true) ) ) ? get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true) : '';
$images[] = array(
'url' => $image_url,
'alt' => $image_alt,
'href' => $image_href // url from WP Gallery Custom Links
);
}
}
}
$image = $images[array_rand( $images, 1 )];
?>
<a href="<?php echo $image['href']; ?>" title="<?php echo $image['alt']; ?>">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
</a>
<?php
}
?>
I'm no programmer so I'm clueless on solutions.
I have been using CMB2
for a Portfolio/Project custom post type.
I've incorporated a slideshow that uses Group Field metadata for each slide.
On the home page there are 2 posts labeled "Empty Project" & "Test Project 1".
If you click the Empty Project you will be directed to it's single post page, there you will see a ".flexslider" div with a red background. That's the div that I would like to remove if the Group Fields are empty. My that I mean completed remove the div leaving no empty divs instead of changing the background color to white.
If you click "Test Project 1", there will be the images uploaded using Repeatable Group Fields within the "flexslider" slideshow. That is to be the result of Metafields that were saved with Metadata inside of them.
METABOX//
Here is the code I have used to register the repeatable fields, which allows me to insert images and captions for the slideshow.
add_action( 'cmb2_admin_init', 'gallery_metabox' );
function gallery_metabox() {
$prefix = 'gallery_';
/**
* Repeatable Field Groups
*/
$cmb_group = new_cmb2_box( array(
'id' => $prefix . 'metabox',
'title' => __( 'Gallery', 'cmb2' ),
'object_types' => array( 'portfolio', ),
) );
// $group_field_id is the field id string, so in this case: $prefix . 'demo'
$group_field_id = $cmb_group->add_field( array(
'id' => $prefix . 'demo',
'type' => 'group',
'options' => array(
'group_title' => __( 'Image {#}', 'cmb2' ), // {#} gets replaced by row number
'add_button' => __( 'Add Another Image', 'cmb2' ),
'remove_button' => __( 'Remove Image', 'cmb2' ),
'sortable' => true, // beta
'closed' => true, // true to have the groups closed by default
),
) );
$cmb_group->add_group_field( $group_field_id, array(
'name' => __( 'Image', 'cmb2' ),
'id' => 'image',
'type' => 'file',
) );
$cmb_group->add_group_field( $group_field_id, array(
'name' => __( 'Image Caption', 'cmb2' ),
'id' => 'image_caption',
'type' => 'text',
) );
}
I followed this to display meta data for those group fields.
Everything works perfectly fine when I use this chunk of code:
FRONT-END//
<div class="flexslider">
<ul class="slides">
<?php $entries = get_post_meta( get_the_ID(), 'gallery_demo', true );
foreach ( (array) $entries as $key => $entry ) {
$img = $img_url = $caption = '';
if ( isset( $entry['image_id'] ) ) {
$img = wp_get_attachment_image( $entry['image_id'], 'share-pick', null, array(
'class' => 'thumb',
) );
}
if ( isset( $entry['image_id'] ) ) {
$img_url = wp_get_attachment_image_url( $entry['image_id'], null );
}
$caption = isset( $entry['image_caption'] ) ? wpautop( $entry['image_caption'] ) : '';
echo '<li data-thumb="'. $img_url .'">';
echo $img;
echo $caption;
echo '</li>';
} ?>
</ul>
</div>
but I would very much like to display the .flexslider container + metadata ONLY when data exist. If fields are empty then I would like to display default text or better yet remove the whole div itself.
I tried my best to do research but I can't seem to figure out what is wrong.
I've also tried this chunk of code as well:
ATTEMPT//
<?php $entries = get_post_meta( get_the_ID(), 'gallery_demo', true );
if(empty ($entry)) { echo ''; }
else {
foreach ( (array) $entries as $key => $entry ) {
echo '<div class="flexslider">';
echo '<ul class="slides">';
$img = $img_url = $caption = '';
if ( isset( $entry['image_id'] ) ) {
$img = wp_get_attachment_image( $entry['image_id'], 'share-pick', null, array(
'class' => 'thumb',
) );
}
if ( isset( $entry['image_id'] ) ) {
$img_url = wp_get_attachment_image_url( $entry['image_id'], null );
}
$caption = isset( $entry['image_caption'] ) ? wpautop( $entry['image_caption'] ) : '';
echo '<li data-thumb="'. $img_url .'">';
echo $img;
echo $caption;
echo '</li>';
echo '</ul>';
echo '</div>';
}
}
?>
The only good thing about the code above is that it definitely removes the div when metafield is empty but if the metadata DOES exist the div is still gone.
EDIT// I tried using "#stweb" code in the answers below:
$entries = get_post_meta( get_the_ID(), 'gallery_demo', true );
foreach ( (array) $entries as $key => $entry ) {
if(empty($entry)){
continue;
}
echo '<div class="flexslider">';
echo '<ul class="slides">';
$img = $img_url = $caption = '';
if ( isset( $entry['image_id'] ) ) {
$img = wp_get_attachment_image( $entry['image_id'], 'share-pick',
null, array( 'class' => 'thumb', ) );
}
if ( isset( $entry['image_id'] ) ) {
$img_url = wp_get_attachment_image_url( $entry['image_id'], null );
}
$caption = isset( $entry['image_caption'] ) ? wpautop(
$entry['image_caption'] ) : '';
echo '<li data-thumb="'. $img_url .'">';
echo $img;
echo $caption;
echo '</li>';
echo '</ul>';
echo '</div>';
}
but nothing happens...the red div just sits there instead of disappearing.
I'd basically like to figure out how I can display the first chunk of code ONLY if images were uploaded to Group Field and if not then display nothing at all not even the container div.
Can anyone please explain where I went wrong?
Try this:
$entries = get_post_meta( get_the_ID(), 'gallery_demo', true );
foreach ( (array) $entries as $key => $entry ) {
if(empty($entry)){
continue;
}
echo '<div class="flexslider">';
echo '<ul class="slides">';
$img = $img_url = $caption = '';
if ( isset( $entry['image_id'] ) ) {
$img = wp_get_attachment_image( $entry['image_id'], 'share-pick',
null, array( 'class' => 'thumb', ) );
}
if ( isset( $entry['image_id'] ) ) {
$img_url = wp_get_attachment_image_url( $entry['image_id'], null );
}
$caption = isset( $entry['image_caption'] ) ? wpautop(
$entry['image_caption'] ) : '';
echo '<li data-thumb="'. $img_url .'">';
echo $img;
echo $caption;
echo '</li>';
echo '</ul>';
echo '</div>';
}
UPDATE:
foreach ( (array) $entries as $key => $entry ) {
if ( !isset( $entry['image_id'] ) || $entry['image_id'] == '' ) {
continue;
}
echo '<div class="flexslider">';
echo '<ul class="slides">';
$img = $img_url = $caption = '';
if ( isset( $entry['image_id'] ) ) {
$img = wp_get_attachment_image( $entry['image_id'], 'share-pick',
null, array( 'class' => 'thumb', ) );
}
if ( isset( $entry['image_id'] ) ) {
$img_url = wp_get_attachment_image_url( $entry['image_id'], null );
}
$caption = isset( $entry['image_caption'] ) ? wpautop(
$entry['image_caption'] ) : '';
echo '<li data-thumb="'. $img_url .'">';
echo $img;
echo $caption;
echo '</li>';
echo '</ul>';
echo '</div>';
}
Basically the format of the image tag I am trying to create is:
<img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" class="attachment-catalog" data-src="my/image/path/here">
And here is my code:
<?php
if ( has_post_thumbnail( $post->ID ) ) {
$newimgdetails = array(
'src' => "data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=",
'class' => "attachment-$size",
'alt' => trim( strip_tags( $attachment->post_excerpt ) ),
'title' => trim( strip_tags( $attachment->post_title ) ),
'data-src' => $src,
);
echo get_the_post_thumbnail( $post->ID, 'shop_catalog', $newimgdetails);
}
?>
I'm fairly new to php so I'm assuming it's an easy fix, but I've been messing around with this for the past hour.
Can someone help me get this one figured out?
Here is a link to the codex for get_the_post_thumbnail - https://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
*Update - Tried this code out with a picture from google and it works. The issue is my variable $src. I need this to get the path to the image, which it is currently not doing. I used $src because I saw it in the codex link above and thought it would work. lol.
I am asuming that you have registered 'shop_catalog' using add_image_size
<?php
if ( has_post_thumbnail( $post->ID ) ) {
$thumb_id = get_post_thumbnail_id( $post->ID );
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'shop_catalog', true);
$src = $thumb_url_array[0];
echo '<img scr="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" class="attachment-catalog" alt="'.trim( strip_tags( $attachment->post_excerpt ) ).'" title="'.trim( strip_tags( $attachment->post_title ) ).'" data-src="'.$src.'">';
}
?>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm trying to get the post thumbnail to change if a user selects a new file on a front end post edit screen. This is similar to the code I use to upload data and set the post thumbnail on a front end add new post form:
<?php
$query = new WP_Query( array( 'post_type' => 'properties', 'posts_per_page' => '-1' ) );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
if(isset($_GET['post'])) {
if($_GET['post'] == $post->ID)
{
$current_post = $post->ID;
$content = get_the_content();
$price = get_post_meta($post->ID, 'shru_price', true);
$address = get_post_meta($post->ID, 'shru_address', true);
$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-image' );
}
}
endwhile; endif;
wp_reset_query();
global $current_post;
$postContentError = '';
if ( isset( $_POST['submitted'] ) && isset( $_POST['post_nonce_field'] ) && wp_verify_nonce( $_POST['post_nonce_field'], 'post_nonce' ) ) {
if ( trim( $_POST['postContent'] ) === '' ) {
$postContentError = 'Please enter a description of this property.';
$hasError = true;
}
$post_information = array(
'ID' => $current_post,
'post_content' => $_POST['postContent'],
'post_type' => 'properties',
'post_status' => 'publish'
);
$post_id = wp_update_post($post_information);
function upload_user_file( $file = array() ) {
global $post_id;
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'], $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
if( ! empty( $_FILES ) ) {
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$attachment_id = upload_user_file( $file );
}
}
}
$propertyfor = $_POST['propertyfor'];
$propertytype = $_POST['propertytype'];
$bedrooms = $_POST['bedrooms'];
if($post_id) {
// Update Custom Meta
update_post_meta($post_id, 'shru_price', esc_attr(strip_tags($_POST['shru_price'])));
update_post_meta($post_id, 'shru_address', esc_attr(strip_tags($_POST['shru_address'])));
update_post_meta($post_id, '_thumbnail_id', $attachment_id );
wp_set_object_terms( $post_id, $propertyfor, 'propertyfor' );
wp_set_object_terms( $post_id, $propertytype, 'propertytype' );
wp_set_object_terms( $post_id, $bedrooms, 'bedrooms' );
// Redirect
wp_redirect(home_url('/listings'));
exit;
}
}
?>
The only difference is that in the code above I am trying to use:
update_post_meta($post_id, '_thumbnail_id', $attachment_id );
instead of:
set_post_thumbnail($post_id, $attachment_id);
For some reason, on the post edit screen the image file does not even upload. When I use update post meta, it removes the old thumbnail, so I guess it's doing it's job there, but since the file isn't uploading it cannot replace it with a new one. The confusion is why the file uploads using the upload_user_file function on the add new post screen but not the edit post screen.
Any ideas?