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.
Related
I have checked similar questions in this forum but I can't find any answers that show me exactly how I can do this.
I've set up a WP page template that lists all categories (and their associated posts) alphabetically, in 2 columns. The display is similar to that shown below:
The code is working fine.
However, I want to change the code so that I can pass it a letter (for example, 'A') so that only Categories beginning with the letter 'A' (or whatever letter is chosen) - and their posts - are shown.
For example, passing the letter 'A' would result in the following display:
The code I'm using is as follows:
<?php
// Grab all the categories from the database that have posts.
$categories = get_terms( 'category', 'orderby=name&order=ASC');
// Loop through categories
echo "<div class='new-column'>";
$counter = 0;
foreach ( $categories as $category ) {
if($counter % 4 == 0 && $counter !=0){
echo "<div class='new-column'>";
}
// Display category name
echo '<h2 class="post-title">' . $category->name . '</h2>';
echo '<div class="post-list">';
// WP_Query arguments
$args = array(
'cat' => $category->term_id,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$customfieldvalue = get_post_meta($post->ID, "PDF", true);
?>
<p><?php the_title(); ?></p>
<?php
} // End while
} // End if
echo '</div>';
// Restore original Post Data
wp_reset_postdata();
$counter++;
if($counter % 4 == 0){
echo "</div>";
}
} // End foreach
if($counter % 4 != 0){
echo "</div>";
}
?>
My question is, how do I edit the code so that a letter ('A', 'B', 'C' etc) can be passed to the code and have only the Categories beginning with that letter displayed?
UPDATE
It's been suggested that Lafif Astahdziq's solution, posted some time ago in answer to another question, is also an appropriate answer to my question.
At a casual glance it may be. However, having read Lafif's answer, I'm afraid I cannot understand how his code works and how I might use it to improve my code and solve my question.
If a particular answer 'works perfectly' but cannot be understood by the individual posing the question, is that a satisfactory outcome?
If I accept Lafif's answer, then I'll have to ask a further question - how do I use Lafif's code?
Finally, I am not trying to deride Lafif's answer in any way. I'm sure it was made with the best of intentions in response to the earlier question.
You could do a custom query to the Wordpress database, where you send the search letter in the URL.
Where the query would be something like(simplified):
$letter = $_GET['firstLetter'];
$sql = "SELECT * FROM wp_posts WHERE cat_name LIKE '" . $letter . "%' ";
You can read about the database relations regarding taxonomies here
I think I am pretty close to the solution but I cannot figure out the logic for where I should close the last div.
I have a wordpress query which requests four posts.
I want to wrap every two items in <section class="sponsor-row">
So I have implemented a counter in my query that counts each post, and if it finds two posts have been output it closes the <section> div off.
But I cannot work out how I should work out if the row should be closed again.
Can anyone figure this out? How can I make it wrap every two outputs in <section class="sponsor-row"> ?
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$counter = 0;
echo '<section class="sponsor-row">'; // Opening the section here
if ( has_post_thumbnail() ) {
$counter++;
echo '<div class="grid half">';
echo '<a class="sponsor" href="'.get_the_permalink().'" target="_blank">';
the_post_thumbnail( 'full' );
echo '</a>';
echo '</div>';
if ($counter <= 2){
echo '</section>'; // closing the section if two posts
$counter = 0;
}
}
}
}
Full query here: http://pastebin.com/e6RzZLR5
if you do if ($counter <= 2){ then it will close it each time it is less or equal 2, which means it will close it twice for each item. You should use if ($counter == 2){ and $counter = 0; should be at the top before the query, otherwise you will set it to 0 each loop.
See comparison in php
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();
?>
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'm creating a custom Google map that plots multiple markers.
View the link as it will make it easier to explain what is happening and what I want
If you click on each marker it shows company names that are grabbed from the child pages. At the moment it's showing ALL the company names on each marker. How can I show just one company name per marker? i.e So one say "MediWales" and the other says "Teamworks Design & Marketing", and so on when I add more companies.
Here's the code controlling the little popup:
<?php $pages = get_pages(array('child_of' => 1873, 'sort_column' => 'menu_order'));
$counter = 1;
foreach($pages as $post)
{
setup_postdata($post);
$fields = get_fields(); ?>
<p><?php $counter++; echo $fields->company_name;?></p>
<?php } wp_reset_query(); ?>
Once it's looped through once, the next time it loops through I need it to start on the next child and not show the first one.
UPDATE:
It seems like it's very close, it's showing one company but the same one on both markers.
<?php
$counter = 1;
$pages = get_pages(array('child_of' => 1873, 'sort_column' => 'menu_order', 'offset' => $counter, 'number' => 1));
foreach($pages as $post) {
setup_postdata($post);
$fields = get_fields(); ?>
<p><?php echo $fields->company_name; echo $counter; ?></p>
<?php $counter++; }
wp_reset_query(); ?>
Your issue is the fact that PHP is by nature preprocessed. JavaScript doesn't run that PHP everytime you click that marker.
Your best bet is to output a JSON object from PHP containing all the markers and their attributes, then parse it dynamically with JavaScript.