I'd like to be able to able to swap an img's src value with a variable created in PHP.
I currently am using javascript to determine the device width. This is happening within the .php file containing the Wordpress loop. Upon recognizing the device width, I would like to change the img's src value accordingly.
I can successfully retrieve the PHP variables using this JS function however only when the function is written in the loop, and as you all know, this will duplicate the function for each post and is resulting in an error.
I need to be able to calculate these given PHP variables outside the loop and then inject them into the img src value inside the loop.
I recognize I may have more errors in this code than what I am looking to resolve! I have been working on this for some time and this particular issue has become quite troubling. Thanks in advance.
Current Code in Use:
<?php query_posts( array ( 'home' => 'WordPress Themes', 'orderby' => 'rand', 'posts_per_page' => -1 ) ); ?>
<?php while ( have_posts() ) : the_post(); ?>
<script>
function getImagePath(){
if (window.matchMedia('(max-device-width: 1920px)').matches) {
var theSizedImage = <?php the_field('desktop_image'); ?>
}if (window.matchMedia('(max-device-width: 1280px)').matches) {
var theSizedImage = <?php the_field('tablet_image'); ?>
}if (window.matchMedia('(max-device-width: 600px)').matches) {
var theSizedImage = <?php the_field('mobile_image'); ?>
}
return theSizedImage;
}
</script>
<img src="pixel.gif" onload="this.onload=null; this.src=getImagePath();" />
<?php endwhile;
wp_reset_query();
?>
So after much further tinkering, I was able to come up with a solution.
This does in fact work, however I wonder if there is a far more elegant solution.
You will note my query has changed slightly as I improved the page and took care of errors. The main problem with the above code was that the variables for the image URLs were getting defined only once. The solution I have provided below will rerun for each of the posts in the loop.
<?php query_posts( array ( 'category__not_in' => array( 1, 4, 5, 6, 7 ), 'orderby' => 'rand', 'posts_per_page' => -1 ) ); ?>
<?php while ( have_posts() ) : the_post(); ?>
<script>
if (screen.width <= 1920) {document.write("<img src='<?php the_field('desktop_image');?>' />");}
if (screen.width <= 1280) {document.write("<img src='<?php the_field('tablet_image');?>' />");}
if (screen.width <= 600) {document.write("<img src='<?php the_field('mobile_image');?>' />");}
if (screen.width > 1920){document.write("<img src='<?php the_field('full_resolution');?>' />");}
</script>
<?php endwhile;
wp_reset_query();
?>
Related
Example:
We got some nice posts that got a link to jump to the next post with scrolling down the page. No reload, new tab or anything just a simple smoothscrolling of the page.
Problem:
We are inside a Wordpress Loop that creates some content from the DB and want to generate a link that jumps to the next run-through that will be generated by the Loop. Within the loop we cant predict what will be the next post/product or whatever post-type the loop should go through. So how am I giving the Link the correct anchor link?
Possible Solutions:
Maybe we can store the data from each run in an array?
Maybe we should create a second loop that only saves the data?
Maybe I should just use JS to rename that anchors after it finishes...
You can add an incremental id with the loop index and assign the anchor to the current index + 1. A simple example:
<?php
global $wp_query;
$args = array(
'post_type' => 'post'
);
$post_query = new WP_Query($args);
if($post_query->have_posts() ) {
while($post_query->have_posts() ) {
$post_query->the_post();
$index = $wp_query->current_post + 1;
?>
<div id="my_post_<?php echo $index; ?>"><?php the_title(); ?></div>
<?php
if (($wp_query->current_post +1) <= ($wp_query->post_count)) {
echo 'Next post';
}
?>
}
}
?>
I am having a loop and that loop has only sticky posts in it. So my logic works like this:
"If Sticky Posts are "EMPTY" break the loop". That code works as expected and looks like this:
<?php //we will get "Sticky Posts" only with this loop and exlude Featured Category
$category = get_cat_ID('Featured');
$col = 1; //Let's create first column
$sticky = get_option( 'sticky_posts' );
$args = array(
/* Add whatever you need here - see http://codex.wordpress.org/Class_Reference/WP_Query */
'paged' => $paged,
'category__not_in' => array($category),
'post__in' => $sticky,
'ignore_sticky_posts' => 1
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query($args);
/*Below is IMPORTANT PART*/
if($wp_query->have_posts()):?><?php while ( $wp_query->have_posts() ) :
$wp_query->the_post();if(empty($sticky))break;?>
<div <?php post_class('col'.$col); ?> id="post-<?php the_ID(); ?>">
<?php if ($col == 1) echo '<div class="row">';//If column 1 create first row ?>
<?php if ($col == 2) echo '<div class="row2">';//If column 2 create second row ?>
<h3 class="mytitle"><?php the_title(); ?></h3>
<div class="entry">
<?php if ( has_post_thumbnail() ):?>
<div class="featured_img">
<?php
the_post_thumbnail();
echo '<div class="featured_caption">' . get_post(get_post_thumbnail_id())->post_excerpt . '</div>';
?>
</div><!--/featured_img-->
<?php endif; ?>
<?php // let's enable more link on pages...
global $more;
$more = 0;
?>
<?php the_content(__('Read more','override')); ?>
<div class="clear"></div>
<div class="custom_fields"><?php the_meta(); ?></div><br/>
<p class="postmetadata">
<?php _e('Filed under:','override'); ?> <?php the_category(', ') ?> <?php _e('by','override'); ?> <?php the_author(); ?><br/><?php the_tags(__('Tags:','override'), ', ', '<br />'); ?>
<?php _e('Posted on: ','override'); ?><?php the_time(get_option('date_format')); ?><br/>
<?php if ( comments_open() ) {
comments_popup_link(__('No Comments »','override'), __('1 Comment »','override'), __('% Comments »','override'));}
else {
_e('Comments are disabled!','override');
}
?>
<?php edit_post_link(__(' Edit','override'), __(' |','override'), ''); ?>
</p>
</div><!--/entry-->
</div><!--/post_class-->
<?php /*Enable Two Column Layout*/
if($col==1) {
$col=2;
echo "</div>";
}
else if($col==2) {
$col=1;
echo "</div>";
}
endwhile; ?>
<?php endif; ?><!--END if THE LOOP (Sticky)-->
<?php
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>
Now before this working code I tried a different logic that goes like this:
"If NOT EMPTY continue the loop" so now everything in my code stays the same except:if($wp_query->have_posts()):?><?php while ( $wp_query->have_posts() ) :
$wp_query->the_post();if(empty($sticky))break;?> so now that code becomes:if($wp_query->have_posts()):?><?php while ( $wp_query->have_posts() ) :
$wp_query->the_post();if(!empty($sticky))continue;?>
Now this is where i got confused because if(!empty($sticky))continue; part does not work as expected because my loop CONTINUES (returns other posts) even if there are no "Stickies". I thought that loop will STOP if there are no stickies but it is not the case. My var_dump($sticky)
shows this if there are sticky postsarray(1) { [0]=> int(214) } and shows this if there are no stickiesarray(0) { }.
My question is: Why the loop continues to return other posts if using if(!empty($sticky))continue; (i thought it will return ONLY "Stickies" if they exist and return NOTHING if they are not here. )
Thank you!!
First off, let me poit out that your logic doesn't quite agree with your code :).
From what I understand from your code, you want to iterate all posts WP_Query() returned, but only render sticky ones. Your if is inside the wile loop, so you have to check if the current post is sticky or not. However, if(empty($sticky)) doesn't do that. It checks if there are any sticky posts at all. A way to check the current post would be if(is_sticky(the_ID())).
Now, concerning continue:
From the php manual:
continue is used within looping structures to skip the rest of the
current loop iteration and continue execution at the condition
evaluation and then the beginning of the next iteration.
So as you can see, continue doesn't stop the loop, but rather attempts to start the next iteration ignoring the rest of the code for the current step. Which is what you want, if the current post is not sticky, in other words if(!is_sticky(the_ID())).
However, I think you don't really need any check at all, since you already specified that you want WP_Query() to fetch only stickies ('post__in' => $sticky).
See also: this WordPress Answers topic.
I don't know well the wordpress code, but in that code, the $sticky variable is never updated in the while loop. So maybe you have to add $sticky = get_option( 'sticky_posts' ); right before the if condition.
I am building a WordPress website where I want a fullscreen homepage background slider.
I really like the jQuery backstretch plugin here: https://github.com/srobbin/jquery-backstretch
(If you take a quick peek at how it works there, choose the second on the Demo dropdown.)
To make the plugin work you need to use this JS snippet:
<script>
$.backstretch([
"http://dl.dropbox.com/u/515046/www/outside.jpg"
, "http://dl.dropbox.com/u/515046/www/garfield-interior.jpg"
, "http://dl.dropbox.com/u/515046/www/cheers.jpg"
], {duration: 3000, fade: 750});
</script>
As you can see, the images need to be declared within the JS. I need to be able to upload as many images as I want, run a loop to get the URL's for each image then display them. I will need to pass these via PHP.
The PHP snippet for getting each image will be: <?php the_field('background_image'); ?>
How can I alter the script to run a loop and get the image/s via PHP?
Thanks in advance
Edit:
This is the loop to display all of my images using ACF plugin and the options page add-on: '
<ul>
<?php while(has_sub_field('slider_images','option')): ?>
<li><img src="<?php the_sub_field('slider_image'); ?>" /></li>
<?php endwhile; ?>
</ul>
<?php endif; ?>'
I managed to do it with the following code:
<?php
$images = get_field('bg_images','option');
if ($images):
foreach($images as $image): ?>
<?php $imageList .= '"'. $image['url'] .'",'; ?>
<?php endforeach;
endif;
$imageList = rtrim($imageList, ',');
?>
<script>
$.backstretch([
<?php echo $imageList; ?>
], {duration: 3000, fade: 750});
</script>
Thanks for the help #mcNab
It depends on how these images are associated with posts/options, that is not clear from your question. The PHP you've suggested there looks like an option attached to an individual page rather than array full of images. However for the sake of your example let's assume that you want to pull the background image out of the first 5 posts in a custom post type called home_slider and use those;
<?php
$imgList = '';
$homeslider_query = new WP_Query(array('post_type' => 'home_slider', 'numberposts' => '5', 'orderby' => 'menu_order', 'order' => 'ASC' ));
if ( $homeslider_query->have_posts() ) :
while ($homeslider_query->have_posts()) : $homeslider_query->the_post();
// Build your list of images
$imgList .= '"'. the_field('background_image') .'",';
endwhile;
endif;
// Trim trailing comma from list
$imgList = rtrim($imgList, ',');
?>
Now, as you have the script tags there that tells me the JS is in the page itself, probably the head, rather than a .js file so;
<script>
$.backstretch([
<?php echo $imgList; ?>
], {duration: 3000, fade: 750});
</script>
I'm trying exhaustively to get a specific row from within a loop using the_meta() array in Wordpress and assigning a variable to it (like the procedural while loop). Right now it simply pulls all of the rows at once. The result from this query returns 3 rows from the database. What I am trying to do it wrap a div tag around one of the returned rows that is stored within the_meta();.
I've tried exploding the array and returning the first row but it just returns everything all at once. I just want to get a row and put it in a variable so that I can style it using CSS.
Here is the code:
$args = array(
'post_type' => 'membersprofile',
'posts_per_page' => 20);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$newvar = explode(" ", the_meta());
echo $newvar[0];
endwhile;
Any help would be greatly appreciated!
EDIT: Thanks to Youn for pointing me in the right direction and finding the answer for me, The problem was I was using the_meta() which only returned the whole rows. By using get_post_meta I was able to assign variables to each row returned. The code that works is:
$key_2_value = get_post_meta(get_the_ID(), 'wpcf-shortbio', true);
// check if the custom field has a value
if($key_2_value != '') {
echo $key_2_value;
}
Hope this helps someone else!
Try using get_post_meta() in place of the meta. It will return the meta value for a specific page/post.
For more info visit at http://codex.wordpress.org/Function_Reference/get_post_meta
In loop you can use
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<p><?php echo post_custom( 'my_meta_key' ) ; ?></p>
<?php endwhile; endif; ?>
I am trying to write a function that will output every other attachment caption and format each nicely within a div containing sequential IDs. However, anytime I add an echo and echo before and after a post_excerpt my code is completely breaking. Based on my HTML output the first echo seems to be ignored until the second time through the loop. The captions seem to post fine if I take out the echo div code.
<?php while ( have_posts() ) : the_post(); ?>
<?php
$argsThumb = array(
'orderby' => 'menu_order',
'order' => 'ASC',
'post_type' => 'attachment',
'post_status' => null,
'post_parent' => $post->ID,
'include' => $thumb_id
);
$thumb_images = get_posts($argsThumb);
$currentThumb = 1;
$captionID=1;
foreach ($thumb_images as $thumb_image) {
if ($currentThumb % 2 == 0)
echo '<div class="caption'.$captionID++.'">';
echo $thumb_image->post_excerpt;
echo '</div>';
$currentThumb++;
}
?>
<?php endwhile; // end of the loop. ?>
Here is my HTML Output, in theory there should be 5 captions based on the fact that I have 10 images and the code is suppose to pull every other image caption:
<div class="caption1"></div>
BEFORE 3</div>
<div class="caption2">CLIENT: ELYSIAN<br>AGENCY: IN HOUSE<br>PHOTOG: JEFF SCIORTINO<br><br><p>THIS IMAGE WAS PART OF A SERIES SHOT FOR THE ELYSIAN. I WAS APPROACHED TO ADD ELEMENTS THAT WERE NOT POSSIBLE TO CAPTURE IN CAMERA.</p></div>
AFTER 2.</div>
<div class="caption3">BEFORE 1</div>
It looks like one problem might be that you've forgotten to wrap the if block in braces.
Right now, what you have is basically this:
foreach ($thumb_images as $thumb_image) {
if ($currentThumb % 2 == 0) {
echo '<div class="caption'.$captionID++.'">';
}
echo $thumb_image->post_excerpt;
echo '</div>';
$currentThumb++;
}
So, you may want to make it look like this, intead:
foreach ($thumb_images as $thumb_image) {
if ($currentThumb % 2 == 0) {
echo '<div class="caption'.$captionID++.'">';
echo $thumb_image->post_excerpt;
echo '</div>';
$currentThumb++;
}
}
This above error is a really good reason to always include braces, even for single-line if blocks.
However, I don't think this will fully fix your issue. I suggest you look at your data again, as you can see that echo '</div>'; is happening five times. My guess is that the foreach ($thumb_images as $thumb_image) loop only has five attachments to grab.