Wordpress use query as AJAX - php

I have a custom field selectbox where I chose which Posts I want to be displayed. Now I want the query, where I get the selected Posts and its custom fields, to somehow be used as an AJAX-call so that I can use the data-output to build a masonry-grid. Is that possible?
here is my data/query:
$posts = get_field('choose_artist');
if( $posts ): ?>
<?php foreach( $posts as $p ): ?>
<div class="artist">
<a href="<?php echo get_permalink( $p->ID ); ?>">
<div style="position: relative;">
<?php $image = get_field('artist_image', $p->ID); ?>
<div class="artist-image" style="background-image:url('<?php echo $image['url']; ?>')"></div>
<div class="overlay">
<div class="content">
<p><?php the_field('artist_name', $p->ID); ?></p>
</div>
</div>
</div>
</a>
</div>
<?php endforeach; ?>
So, my goal is something like:
$.ajax({
url: '/the query above',
success: function(data){
data is the query html
}})
Is that even possible?

ajax.php
$content = '';
if( $posts ) {
foreach( $posts as $p ) {
$image = get_field('artist_image', $p->ID);
$content .= '<div class="artist">';
$content .= '<a href="' . get_permalink( $p->ID ) . '">';
$content .= '<div style="position: relative;">';
$content .= '<div class="artist-image" style="background-image:url("' . $image['url'] . '")"></div>';
$content .= '<div class="overlay">';
$content .= '<div class="content">';
$content .= '<p>' . get_the_field('artist_name', $p->ID). '</p>';
$content .= '</div>';
$content .= '</div>';
$content .= '</div>';
$content .= '</a>';
$content .= '</div>';
}
}
echo $content;
main.js / .php (whereever you have the ajax call)
$.ajax({
url: '/ajax.php', //Path to the ajax.php script
success: function(data){
console.log(data);
}});
Check the documentation for how to catch errors, check for success etc. etc: http://api.jquery.com/jquery.ajax/
There are better ways to do the AJAX page, so refactor it and make it neater, but something similar to the above should work for you if I am understanding your needs, though you'll probably need to tweak it to get what you want.

Related

How do I execute php code within a variable containing html

I assembled a Wordpress shortcode but it throws an error in the block editor: "Updating failed. The response is not a valid JSON response." Notwithstanding, the edits are saved. I've been told the reason I get the error is my "shortcode handler function is generating output. Such functions must collect all output into a variable which is returned."
Below are (1) the code that works but causes the error message and (2) my pseudo code to fix the problem by assigning the 'a href' to a variable $html, but doesn't.
(1)
function make_header() {
$args = array(
'posts_per_page' => 1,
'category_name' => 'headlines',
);
$q = new WP_Query( $args);
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
?>
<a href="<?php the_permalink() ?>">
<div><img src="<?php echo $featured_img_url; ?>" width="100%" /></div>
<h2>
<?php the_title(); ?>
</h2></a>
<?php
}
wp_reset_postdata();
}
}
add_shortcode('make_header', 'make_header');
(2)
$html = '
<a href="<?php the_permalink() ?>">
<div><img src="<?php echo $featured_img_url; ?>" width="100%" /></div>
<h2>
<?php
the_title(); ?> </h2></a>';
}
wp_reset_postdata();
return $html;
Thanks for your help.
Try below code
$html = ' <div><img src="'. echo $featured_img_url .'" width="100%" /></div> <h2>'. the_title().' </h2>';
the concatenation operator (‘.‘), which returns the concatenation of its right and left arguments. 
You could to use concatenation like so:
$html = '<a href="' . esc_url(get_the_permalink()) . '">';
$html .= '<div>';
$html .= '<img src="' . $featured_img_url . '" width="100%" />';
$html .= '</div>';
$html .= '<h2>' . get_the_title() . '</h2></a>';
Also, use get_the_permalink() and get_the_title() as these functions are returning their result instead of outputting it.
The full code would then look something like this:
function make_header() {
$html = '';
$args = array(
'posts_per_page' => 1,
'category_name' => 'headlines',
);
$q = new WP_Query( $args);
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
$featured_img_url = esc_url(get_the_post_thumbnail_url(get_the_ID(),'full'));
$html = '<a href="' . esc_url(get_the_permalink()) . '">';
$html .= '<div>';
$html .= '<img src="' . $featured_img_url . '" width="100%" />';
$html .= '</div>';
$html .= '<h2>' . get_the_title() . '</h2></a>';
}
wp_reset_postdata();
}
return $html;
}
add_shortcode('make_header', 'make_header');

wordpress blog title url

I'm trying to make my blog titles link to the full post from the preview area so the title should have the same function as the read more button. The blogs are in a masonry layout and I'm using a themeforest theme.
This is the blog page.
I believe this to be the php code that controls the layout - hope it helps.
Sorry php newbie here.
I have tried using <h5 class="post-title">'. get_the_title() .'</h5>'; but all this did was generate a broken url containing '.get_permalink().'" in it.
Thank you
<?php if ( '' != get_the_title() ): ?>
<h5 class="post-title"><?php the_title(); ?></h5>
<?php endif ?>
<?php if (has_post_format('link')): ?>
<?php echo __("Read more", TEMPNAME); ?><span class="icon-arrow-right9"></span>
<?php else: ?>
<?php echo __("Read more", TEMPNAME); ?><span class="icon-arrow-right9"></span>
<?php endif ?>
<?php endif; ?>
You just need to wrap the h5 title in an anchor tag <a> on line 37 of your snippet. The specific code to change is:
New Answer
<a href="<?php get_permalink(); ?>">
<h5 class="post-title"><?php the_title(); ?></h5>
</a>
or from you code, try:
<a href="<?php echo $nz_link_url; ?>" title="<?php echo __("Go to", TEMPNAME).' '.$nz_link_url; ?>">
<h5 class="post-title"><?php the_title(); ?></h5>
</a>
Old Answer
if ( '' != get_the_title() ){
$output .= '<h5 class="post-title">'. get_the_title() .'</h5>';
}
You may have to update your CSS to reflect the anchor tag in front of the H5
Full Code
while($recent_posts->have_posts()) : $recent_posts->the_post();
$output .= '<div class="post format-'.get_post_format().'" data-grid="ninzio_01">';
$output .= '<div class="post-wrap nz-clearfix">';
if (get_post_format() == 'image') {
$values = get_post_custom( $post->ID );
$nz_image_url = isset($values["image_url"][0]) ? $values["image_url"][0] : "";
if (!empty($nz_image_url)) {
$output .='<a class="nz-more" href="'.get_permalink().'">';
$output .= '<div class="nz-thumbnail">';
$output .= '<img src="'.$nz_image_url.'" alt="'.get_the_title().'">';
$output .= '<div class="ninzio-overlay"></div>';
$output .= '<div class="post-date"><span>'.get_the_date("d").'</span><span>'.get_the_date("M").'</span></div>';
$output .='</div>';
$output .='</a>';
}
} else {
if (has_post_thumbnail()) {
$output .='<a class="nz-more" href="'.get_permalink().'">';
$output .= '<div class="nz-thumbnail">';
$output .= get_the_post_thumbnail( $post->ID, $size );
$output .= '<div class="ninzio-overlay"></div>';
$output .= '<div class="post-date"><span>'.get_the_date("d").'</span><span>'.get_the_date("M").'</span></div>';
$output .='</div>';
$output .='</a>';
}
}
$output .= '<div class="post-body">';
if ( '' != get_the_title() ){
$output .= '<h5 class="post-title">'. get_the_title() .'</h5>';
}
if ($excerpt == "true") {
$output .= '<div class="post-excerpt">'.nz_excerpt(95).'</div>';
}
$output .=''.__("Read more", TEMPNAME).' <span class="icon-arrow-right9"></span>';
$output .= '</div>';
$output .= '</div>';
$output .= '</div>';

ajax load content render in php return

I'm using ajax call api return json and render html append to page like below.
I have question is is possible after post parameter to api function then api function render in php then return rendered data to js, js just only append?
Because there is to much html structure if i write in js so difficult to read. Wondering most people how to do this?
$.ajax({
url: public_path+'/api_for_ajax/category/'+category_id+'/'+visible+'/'+rows_perpage+'/'+page,
type: 'POST',
processData: false,
contentType: false,
async: false
}).done(function(response) {
var response = JSON.parse(response);
$(data_article.article).each(function(i, each_data_article) {
var output = '<div class="article-list"><a href="'+public_path+'/article/'+each_data_article.id+'">
<div class="thumbnail"><img src="'+public_path+'/assets/thumbnails/'+each_data_article.thumbnail.thumbnail_id+'/'+each_data_article.thumbnail.file_name+'.'+each_data_article.thumbnail.file_format+'" alt=""></div>
<div class="subject">'+each_data_article.subject+'</div>
</a></div>';
// append
});
});
api
$data_select_category_id_page = $this->article_model->select_category_id_page($response_message, $category_id, $visible, $rows_perpage, $page);
$data = array();
$data['article'] = $data_select_category_id_page;
echo json_encode($data);
I tried in slim framework, it not work why??
api
$data_select_category_id_page = $this->article_model->select_category_id_page($response_message, $category_id, $visible, $rows_perpage, $page);
// 1
$app->render('frontstage/article/page_view.php', array(
'data_select_category_id_page' => $data_select_category_id_page,
)
);
// 2
return <<<HTML
<div><?php print_r($data_select_category_id_page);?></div>
HTML;
layout
<?php $column_count = 1; ?>
<div class="row">
<?php foreach ($data['article']['article'] as $i => $each_article) { ?>
<?php if ($i >= 4) { ?>
<div class="article-list">
<a href="<?php echo $uri['public']; ?>/article/<?php echo $each_article['id']; ?>">
<div class="thumbnail"><img src="<?php echo $uri['public']; ?>/assets/thumbnails/<?php echo $each_article['thumbnail']['thumbnail_id']?>/<?php echo $each_article['thumbnail']['file_name']?>.<?php echo $each_article['thumbnail']['file_format']?>" alt=""></div>
<div class="subject"><?php echo $each_article['subject'];?></div>
<div class="category-list-container">
<?php foreach ($each_article['category'] as $each_article_category) { ?>
<div class="category-list"><?php echo $each_article_category['subject']; ?></div>
<?php } ?>
<div class="clear"></div>
</div>
<?php
$old_date = $each_article['create_at'];
$old_date_timestamp = strtotime($old_date);
$new_date = date('d M Y', $old_date_timestamp);
?>
<div class="create-at"><?php echo $new_date;?></div>
</a>
</div>
<?php if (($column_count % 4) == 0) { ?>
<div class="clear"></div></div><div class="row">
<?php } ?>
<?php $column_count++;?>
<?php } ?>
<?php } ?>
<div class="clear"></div>
It is possible to have the server return the html rendered rather than JSON.
$.post( "ajax/test.php", function( data ) {
$( ".result" ).html( data );
});
Where test.php returns some kind of HTML data.
The test.php code will contain the logic to render the relevant html. Using the OP example as the logic, would look something like (untested) :
$public_path = '/sitepath/';
foreach($data_select_category_id_page as $article)
{
echo '<div class="aricle-list"><a href="' . $public_path . '/article/' . $article->id . '">
<div class="thumbnail"><img src="' . $public_path . '/assets/thumbnails/' . $article->thumbnail_id . '/' . $article->thumbnail->file_name . '.' . $article->thumbnail->file_format . '" alt=""></div>
<div class="subject">' . $article->subject . '</div>
</a></div>';
}
Or alternatively use a layout to render the html.
Beaware that the size of the rendered html being returned from the server is large than JSON.

wordpress ignores formatting when using template tags in functions.php

I am using the following code to create a shortcode for use in the WYSIWYG.
function consultants( $atts, $content = null ) {
$output = '';
$consultant_query = new WP_Query('post_type=consultants&showposts=10');
if ($consultant_query->have_posts()) :
$output .= '<div class="col-md-12">';
while ($consultant_query->have_posts()) : $consultant_query->the_post();
$output .= '<div class="col-xs-12 col-sm-5 col-md-4 kam-tile-own-bg"><h1>' .the_title(). '</h1> ';
if(has_post_thumbnail())
{
$output .= get_the_post_thumbnail($post->ID,'wpbs-featured-avatar');
} else {
$output .= '
<img class="kam-avatar" width="62" height="62" src="'.get_template_directory_uri().'/images/avatar#2x.jpg" class="attachment-featured_image wp-post-image" alt="" />'; }
$output .= '</div>';
endwhile;
$output .= '</div>';
endif;
wp_reset_postdata();
return $output;
}
The code works fine - HOWEVER it fails on the .the_title(). it throws this at the top of the page it has no respect for the tags or the in which it is contained.
Many thanks
instead of the_title(); use get_the_title();

Wordpress: Wrapping two posts into one div

I'm using Foundation for a wordpress theme and I need to wrap two posts into one div with class of 'row'. The thing is I need to put div class="row" before the first post closing the the second post with div and it should repeat with every new posts.
Here is my code:
<?php query_posts( 'cat=2&showposts=9&orderby=date&order=DESC' ); ?>
<div <?php post_class('small-12 medium-6 large-6 columns') ?> id="post-<?php the_ID(); ?>">
<?php echo '<a href="', get_permalink(), '">';
if ( has_post_thumbnail() ) {the_post_thumbnail();}
else { echo '<img src="', get_template_directory_uri( 'template_directory' ), '/images/thumb-default.png','" alt="" />'; }
echo '</a>';
?>
<h3><?php the_title(); ?></h3>
<p><?php echo get_excerpt(); ?></p>
</div>
something like this i think
<?php
$count = 1;
$outputstring = "";
ur while loop
if ( $count % 2 != 0 )
{
$outputstring .= " <row div>";
}
$outputstring .= "<div" . post_class('small-12 medium-6 large-6 columns'). ' id="post-'. the_ID() .'>';
YOUR OUTPUT CODE HERE
if ( $count % 2 == 0 )
{
$outputstring .= " </end row div>";
}
$count++;
END your while loop
echo $outputstring; /// here is where u output the WHOLE thing outside of your loop
?>

Categories