How to format PHP queries for jSON AJAX requests - php

I have a working AJAX function within WordPress, There I'm looping through HTML to get my posts which then are accessible in my AJAX Success CB where they are appended to their div.
My question:
How would I format my PHP query func values (a while loop, an array and several separate pagination values) for proper use within JavaScript?
Here's what my function looks like as is;
<?php
function _custom_paginate(){
$paged = $_POST['count'];
$args = array(
'posts_per_page' => 12,
'category' => 3,
'paged' => $paged,
'post_status' => 'publish'
);
$query = new WP_Query($args);
if ( $query->have_posts() ) :
while ($query->have_posts()) : $query->the_post(); ?>
<div class="large-3 three columns box">
<div class="thumb">
<?php the_content();?>
<div class="thumb-foot">
<div class="thumbinfo">
<p>Posted on <?php the_time('m.d.Y') ?></p>
</div>
<div class="thumb-social">
<div class="thumb-twitter"></div>
<div class="thumb-facebook"></div>
</div>
</div>
</div>
</div>
<?php
endwhile;
endif;
//Several pagination values
$total_pages = $query->max_num_pages;
if ($total_pages > 1){
$current_page = max(1, get_query_var('paged'));
?>
<div class="pagi-contain">
<div id="pagi" class="large-12">
<!-- Append pagination here #pagi-->
<ul class="pagi">
<li id="ajaxprev" style="float:left;">prev</li>
<li id="pagenum"><?php echo $current_page; echo ' ... '.$total_pages; ?></li>
<li id="total_pages"></li>
<li id="ajaxnext" style="float:right;">next</li>
</ul>
</div>
</div>
<?php
}
exit;
}
You don't have to rewrite this but a lesson in formatting each value into an accessible array(?) for JS to work with each value separately. I found this person seems to have done what I am trying but the subject here is not PHP side...
Here is an example that is hopefully more clear on what I'm attempting to make work. http://jsfiddle.net/BenRacicot/LRmc3/

I'm not 100% clear what data you want to format, but just do this:
json_encode($variable_you_want_as_json);
To format the entire page's output, use this:
ob_start(); // Start output buffering (echos after this go into the buffer, not to the client)
// all the code and output you want formatted
// example: echo "Some HTML I want to store in a JSON-encoded variable";
$html_data = ob_get_contents(); // Gets the contents of the buffer
ob_end_clean(); // empties the buffer
echo json_encode($html_data); // encodes and echoes whatever you did between ob_start() and ob_get_contents()
It sounds like you want multiple values, so you can just replace the variable in the last line with an array, like this:
$my_array = array('html_data'=>$html_data,
'max_num_pages' => $query->max_num_pages,
'foo'=>$foo,
'bar'=>$bar,
'some_other_var' => $some_other_var);
echo json_encode($my_array);

Related

While Loop displays arguments inside the first argument

I have a while loop created to display all my wordpress posts. The issue is that all the posts (except the first) appear inside the first post.
I've check my div structures and I couldn't find any issues.
The loop is working, but the div isn't showing in the right place.
<div class="slider-vertical">
<!-- This is the main loop for the posts -->
<?php
$count = 0;
while ( $all_posts->have_posts() ) : $all_posts->the_post();
$count++;
// Variabled for the specific fields (color, 3D objects and so on...)
$fond_couleur = get_field('fond_de_couleur_hex');
$visuel_3D = get_field('source_iframe_3d');
$visuel_3D_2 = get_field('source_iframe_3d_2');
// get_template_part( 'template-parts/content', 'portfolio' );
$content = get_the_content();
$content = apply_filters( 'the_content', $content );
$content = str_replace( ']]>', ']]>', $content );
$gallerieArray = get_field('image_galerie');
$title = get_the_title($post);
?>
<!-- HTML structure for the posts - this is displayed, but only the first one is at the right place -->
<?php
echo '<div class="post-numero';
if($count == 1){
echo ' actif';
}
echo '">';
?>
<!-- DIV that contains the 3D object -->
<div class="visuel-3d" style="background:<?php echo $fond_couleur;?>;">
<!-- Injecting the 3D Object via an iframe -->
<div class="slider-horizontal">
<?php echo '<span class="post-horizontal actif">'. $visuel_3D .'</span>';?>
<?php if($visuel_3D_2){
echo '<span class="post-horizontal">'. $visuel_3D_2 .'</span>';
} ?>
</div>
<h2 class="titrePost"><?php echo $title; ?></h2>
</div>
<!-- Cross used to close the rightside menu -->
<span class="arrow-right-sidebar">x</span>
<!-- HTML structure for the rightside menu -->
<div class="right-sidebar-content foo">
<div class="right-top">
<h2 style="text-align: center;"><?php echo $title; ?></h2>
</div>
<div class="right-bottom">
<div><?php echo $content ?></div><!-- That is where the next posts of the while loop get printed -->
<div class="gallerie-sidebar-full">
<?php // loop for the image gallery at the bottom of the rightside menu
if ($gallerieArray == true){
foreach($gallerieArray as $key => $val){
$gallerieImages[] = $val["url"];
}
$idg = 0;
foreach ($gallerieImages as $val){
echo '<img id="id-'. $title .'-'. $idg .'" class="gallerie-sidebar" src="'. $val .'">';
$idg += 1;
}
}
?>
</div>
</div>
</div>
</div>
<?php
endwhile;
?>
</div>
What is expected is 4 different posts inside the "slider-vertical" div displayed at the same level in the HTML structure.
The actual result is the first post at the correct level and then the next posts 2 levels deeper inside the first post.
this kind of problem occurs when there is a not properly closed HTML tag on the first execution of the loop, try to use a short statement syntax
echo '<div class="post-numero'. (($count == 1)? ' actif' : '').'">;
check also the content printed by <?php echo $content ?> of the first post, may contains an open HTML tag.
You can easily check the generated code using the souce view (CTRL+U) in Firefox that highlights in red the wrong HTML closing tags

Count how many rows are in sub_field

I am using advanced custom field repeater to load some sub_fields which you can see in the below code:
<?php
if( get_field('who_made_it') ): ?>
<div id="role-wrapper">
<?php while( has_sub_field('who_made_it') ): ?>
<div class="role-item">
<?php the_sub_field('job_role'); ?>
<?php the_sub_field('description'); ?>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
I would like to count how many .row-item's there are and then print that number as a class on the container #role-wrapper .
So as a HTML demo of how it would look:
<div id="role-wrapper" class"roleitems-3">
<div class="role-item">
content in here
</div>
<div class="role-item">
content in here
</div>
<div class="role-item">
content in here
</div>
</div>
As specified by the docs, get_field() returns an array() of sub fields in this case. As a result, you can do a simple count():
<div id="role-wrapper" class"roleitems-<?php echo count( get_field('who_made_it') ); ?>">
I am unfamiliar with has_sub_field and the advanced custom field repeater, but it seems a simple answer would be to add a counter.
<?php
$counter = 0;
while( has_sub_field('who_made_it') ):
//do stuff
$counter++;
endwhile;
//output the counter however you like
echo('<div class="counter">Total: ' . $counter . '</div>');
?>

Change Post Title Color dynamically in wordpress

i want to change post title color dynamically like this
<h3 class="green">Post title 1</h3>
<p>post Text</p>
<h3 class="blue">Post title 1</h3>
<p>post Text</p>
<h3 class="orange">Post title 1</h3>
<p>post Text</p>
<h3 class="red">Post title 1</h3>
<p>post Text</p>
<h3 class="yello">Post title 1</h3>
<p>post Text</p>
I limit posts_per_pge = 5, so when a new post ad its title color change in GREEN
Any idea how can i do this any........idea
You can do it by simply as:
first add a custom field with each post and decide which color for that post title
now just get this meta field in your query and change title style
<h2 style="color:<?php echo $meta_color; ?>"> <?php the_title(); ?> </h2>
may this help you...
Count post with a variable and when its 5 return to zero. Then use that to echo diffetent classes. For example something like:
$post_count=0;
$class = "";
if (have_posts() ){....
$post_count .= 1;
if($post_count == 1) $class = "green";
// same with 2, 3, 4 and so on
<h3 class="<? echo $class; ?>">title</h3>
<p>post Text</p>
if($post_count == 4) $post_count = 0;
}// end loop
While Dk-Macadamias solution is a bit more flexible (allowing you to change color on a per-post basis) a more automatic alternative would be to let the post order decide and output the color from a predetermined array.
In your template file:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h3 class="<?php echo get_post_color_class(); ?>"><?php the_title(); ?></h3>
<?php endwhile; endif; ?>
In your functions.php
function get_post_color_class() { //Declare our custom function
global $wp_query; //Import the global $wp_query object
$colors = array('green','blue','orange','red','yellow'); //Declare our array of colors
return $colors[$wp_query->current_post]; //Return the item in our array with the same index as the current post in the loop
}
If you want to alter between two colors you can do it like this. This function will actually count at all posts on a page and not look at the global post ID
function get_post_color_class() { //Declare our custom function
global $wp_query; //Import the global $wp_query object
$colors = array('#D8D32B','#D12F4E'); //Declare our array of colors
return $colors[($wp_query->current_post % 2 != 0) ? 0 : 1];
//Return the item in our array with the same index as the current post in the loop
}
In my case I wanted to alter and change the border-color of a post in wordpess. I did it like this in the content.php:
<article id="post-<?php the_ID(); ?>" <?php post_class( ); ?>
style="border-left-color:<?php echo get_post_color_class(); ?>" >
More than two colors goes like this:
function get_post_color_class() { //Declare our custom function
global $wp_query; //Import the global $wp_query object
$colors = array('#D8D32B','#D12F4E', '#009562'); //Declare our array of colors
if($wp_query->current_post % 3 == 0){
return $colors[2];
}
if($wp_query->current_post % 2 == 0){
return $colors[1];
}
return $colors[0];
}
Alternativly you could resolve it with CSS:
http://www.w3schools.com/cssref/sel_nth-of-type.asp
This should be more elegant and faster.

Wordpress: Getting Month by Month posts, issue with layout

I've got an issue where I'm getting the wordpress posts month by month, but I'm missing something obvious where by it screws with my layout a bit. I'm using the 996 grid system for my layout.
The NEED:
I'm getting all posts in March 2013 and wanting to lay them out each inside a so 3 posts are stacked like screenshot A.
My code is below:
<div class="container clearfix" style="background:yellow;">
<div class="grid_12" style="background:blue;">
<?php
$blogtime = date('Y');
$prev_limit_year = $blogtime - 1;
$prev_month = '';
$prev_year = '';
$args = array(
'posts_per_page' => 20,
'ignore_sticky_posts' => 1
);
$postsbymonth = new WP_Query($args);
while($postsbymonth->have_posts()) {
$postsbymonth->the_post();
if(get_the_time('F') != $prev_month || get_the_time('Y') != $prev_year && get_the_time('Y') == $prev_limit_year) {
echo "<h2>".get_the_time('F, Y')."</h2>\n\n";
}
?>
</div>
<div class="grid_4" style="background:red;">
<article id="post-<?php the_ID(); ?>" role="article" itemscope itemtype="http://schema.org/BlogPosting">
<?php the_post_thumbnail('standard-thumb'); ?>
<h3><?php the_title(); ?></h3>
</article>
</div>
<?php
$prev_month = get_the_time('F');
$prev_year = get_the_time('Y');
}
?>
</div> <!-- END OF CONTAINER -->
THE PROBLEM:
With the above code, every single instance of grid_4 sits outside the container EXCEPT the first one. See Screenshot B
How can I make sure all grid_4 divs are included inside the container?
I've tried moving the div which doesent work, I think I'm missing something fundamental from the query.
So it seems if I remove the closing div to grid_4 - it now works...
In the dom it now all sits inside the container... however looking at the template markup code I'm one div short...
I don't know why this is happening but it is... one day I'll figure out why but right now wordpress is automagically adding an extra div.

Child page content

I have a parent page that acts as menu for my portfolio.
It pulls in thumbnail images from the child pages which i have been able to accomplish with magic fields and some code. It dumps the images into a grid layout. The thumbnails are pulled into one container div like so:
div id="folio-content">
<div class="thumb-container">
<div class="thumb"><img src="/images/pic.jpg"/>
</div>JCPenny</div>
... </div>`
when the div gets filled up with 2 thumbnails I want to create a new container div and fill it with 2 images again and so on after 2 images.
So, if you had 4 images it would look like this.
<div id="folio-content"><!--/Main Container/-->
<div class="thumb-container">
<div class="thumb"><img src="/images/pic1.jpg"/>
</div>JCPenny</div>
<div class="thumb-container">
<div class="thumb"><img src="/images/pic1.jpg"/>
</div>Champ Car</div></div>
<div id="folio-content"><!--/Main Container/-->
<div class="thumb-container">
<div class="thumb"><img src="/images/pic1.jpg"/>
</div>JCPenny</div>
<div class="thumb-container">
<div class="thumb"><img src="/images/pic1.jpg"/>
</div>Champ Car</div></div>
this is the code I am using in my page.php file.
<?php get_header(); ?>
<div id="folio-content">
<?php
$projectpage = get_pages('child_of='.$post->ID.'&sort_column=post_date&sort_order=desc');
$count = 0;
foreach($projectpage as $page)
{
$content = $page->post_content;
if(!$content)
continue;
if ($count == 10) --- this is geting 10 images now, but I want to get them all.
break;
$count++;
$content = apply_filters('the_content', $content);
?>
<div class="thumb-container">
<div class="thumb"><a href="<?php echo get_permalink($page->ID); ?>"<?php echo get_image ("thumbnail",1,1,1,$page->ID);?></a>
</div><?php echo $page->post_title ?>
</div>
<?php
}
?>
</div><!--/close set!-->
</div>
also, how can I get ALL child pages? I have it set to 10 now with this if ($count == 10)
any help? thanks a ton again!!!!
I'm not familiar with "get_pages" but since Wordpress treats posts and pages in an identical manner you could use this.
$projectpage = get_posts('numberposts=-1&post_type=page&child_of='.$post->ID.'&sort_column=post_date&sort_order=desc');
The -1 removes the limit and gets ALL the specified pages.
I have cobbled together some code, that sort of sounds right but does not work at all! Which I am not surprised. But it is a starting point - please take a look at this code, maybe it is step in the right direction?
<?php
$projectpage = get_posts('numberposts=-1&post_type=page&child_of='.$post->ID.'&sort_column=post_date&sort_order=desc');
if (have_posts()) :
$i=0; // counter
while(get_posts()) : the_post();
if($i%2==0) { // if counter is multiple of 3, put an opening div ?>
<!-- <?php echo ($i+1).'-'; echo ($i+2); ?> -->
<div>
<?php } ?>
<div class="single_item">
<h2><?php the_title(); ?></h2>
</div>
<?php $i++;
if($i%2==0) { // if counter is multiple of 3, put an closing div ?>
</div>
<?php } ?>
<?php endwhile; ?>
<?php
if($i%2!=0) { // put closing div here if loop is not exactly a multiple of 3 ?>
</div>
<?php } ?>
<?php endif; ?>

Categories