I have one custom post type and I have created one select field with acf. I need to remove into loop, egual result of option.
<?php
$args = array(
'post_type' => 'agentiestero',
'post_status' => 'publish',
'posts_per_page' => 150,
'orderby'=> 'title',
'order' => 'ASC'
);
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<option value="<?php the_field('localita_estero'); ?>"><?php the_field('localita_estero'); ?></option>
<?php endwhile; ?>
<?php endif; ?>
Iterating over posts is not the best option here. What you most likely want is to iterate over the choices of your ACF select field. To do this, you have to find out your field's field key (e.g., field_5bf68deadbeef) and obtain the field object to get all possible choices from there.
Replace your loop above by the following:
$localization_field = get_field_object('field_5bf68deadbeef');
foreach ($localization_field['choices'] as $key => $label) {
?>
<option value="<?= $key ?>"> <?= $label ?> </option>
<?php
}
This code will obtain the definition of your Select field and iterate over all possible choices. Assuming your choices are value:text pairs, it will insert the value as <option value="..."> and the text as the label.
Use an array to clean up result:
<?php
$result = array();
if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post();
$field = get_field('localita_estero');
if(in_array($field,$result))
continue;
$result[] = $field;
?>
<option value="<?php echo $field; ?>"><?php echo $field; ?></option>
<?php endwhile; ?>
<?php endif; ?>
Related
I've created an Ajax post filter for a blog. When you click a category to filter the posts below, what happens is odd. The markup of the current page is injected rather than the results of my WP_Query arguments. So you end up with the page nested within itself.
Here's my post filter bar with the initial query populating the response div:
Here's the form:
<form action="<?php echo admin_url('admin-ajax.php'); ?>" method="POST" id="filter">
<label><input type="radio" name="category" value="" checked="checked"><div>All</div></label>
<!-- Loop Selected Categories -->
<label><input type="radio" name="category" value="Category_ID"><div>Category Name</div></label>
<!-- End Loop Selected Categories -->
<input type="submit" value="Submit">
<input type="hidden" name="action" value="myfilter">
</form>
Below is my JavaScript:
jQuery(document).ready(function($) {
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:ajax_object.ajaxurl,
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
success:function(data){
$('#response').html(data); // insert data
}
});
console.log('form submitted');
return false;
});
$('#filter input[type=radio]').on('change', function() {
$("#filter").submit();
});
});
Below the filter form there's a response div that contains the initial/default query results:
<div class="post-grid" id="response">
<?php
$args = array(
'posts_per_page' => 5,
'post_status' => array('publish')
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
return get_template_part( 'template-parts/content-card' );
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
?>
</div>
I have the following code to query the selected category in my functions.php:
// In my enqueued scripts
wp_enqueue_script( 'post_filter_js', get_template_directory_uri() . '/dist/js/post-filter.min.js', array('jquery'), '', true );
wp_localize_script( 'post_filter_js', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
// Function to query the selected category
add_action('wp_ajax_myfilter', 'filter_post_by_cat');
add_action('wp_ajax_nopriv_myfilter', 'filter_post_by_cat');
function filter_post_by_cat(){
// for taxonomies / categories
if( isset( $_POST['category'] ) ):
$args = array(
'category__in' => $_POST['category'],
'posts_per_page' => 5,
'post_status' => array('publish')
);
endif;
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo get_template_part( 'template-parts/content-card' );
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
I am trying to load my sidebars in my while loop by using if statements that call them after a certain number of posts. It's important to note that I am using AJAX code (provided below) to load in posts on scroll and I believe it may be causing the issue.
Though they are sidebars, they are not physically a sidebar but rather content loaded between posts.
I've tried for a week to locate the problem but I cannot seem to get the sidebars to load with AJAX as a if statement in the while loop.
Important to note: The sidebar will load after the number of posts if it's not loaded through AJAX. So if it's in the initial load, the sidebars load. But when you continue to scroll to say the third or fourth bar it will not load and the AJAX will only load the (parts/content).
I need to either be able to resolve the if statement so it works within the while loop that loads through AJAX or I'm open to an alternate solution as long as it doesn't remove the AJAX.
A lot of work has been put into making this loop work and help is greatly appreciated!
front-page.php
<?php
$current_page = max( 1, get_query_var( 'paged' ) );
$the_query = new WP_Query( array(
'cat' => '-21',
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => $current_page,
'tax_query' => array(
array(
'taxonomy' => 'topics',
'operator' => 'NOT EXISTS',
'field' => 'term_id',
'terms' => $term_id
)
)
) );
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ),
'posts' => json_encode( $the_query->query_vars ),
'current_page' => $current_page,
'max_page' => $the_query->max_num_pages
) );
?>
<div id="main" class="container-fluid">
<?php if ($the_query->have_posts()) : ?>
<?php $count = 0; ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); get_template_part( 'parts/content', get_post_format() ); ?> <!-- This parts/content loads -->
<?php $count++; ?>
<!-- the dynamic_sidebar does not load -->
<?php if ($count == 2 && is_active_sidebar('sidebar1') ) : ?>
<div class="side-container first-side">
<?php dynamic_sidebar('sidebar1'); ?>
</div>
<?php endif; ?>
<?php if ($count == 10 && is_active_sidebar('sidebar2') ) : ?>
<div class="side-container first-side">
<?php dynamic_sidebar('sidebar2'); ?>
</div>
<?php endif; ?>
<?php if ($count == 20 && is_active_sidebar('sidebar3') ) : ?>
<div class="side-container third-side">
<?php dynamic_sidebar('sidebar3'); ?>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
</div><!-- END CONTAINER -->
parts/content -- this loads as expected including code if it's helpful
<div class="row post"> <!-- Post is mentioned in the below JS to load -->
<div class="col-sm-5">
<h2>Text</h2>
</div>
<div class="col-sm-7">
<h3>text</h3>
</div>
</div><!-- END ROW-->
sidebar code - works when initially loaded but doesn't when AJAX calls on this code such as the last two sidebars in front-page.php
<?php
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?>
<?php while( $flexible_posts->have_posts() ) : $flexible_posts->the_post(); global $post; ?>
<div class="sidebar-area">
//sidebar code here
}
endwhile;
?>
myloadmore.js - AJAX Call
jQuery(function($){
var canBeLoaded = true,
bottomOffset = 2000;
$(window).scroll(function(){
if ( misha_loadmore_params.current_page >= misha_loadmore_params.max_page ) {
return;
}
var data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data: data,
type: 'POST',
beforeSend: function( xhr ){
// AJAX call is in process, we shouldn't run it again until complete
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#main').find('div.post:last-of-type').after( data ); // where to insert posts
canBeLoaded = true; // the ajax is completed, now we can run it again
misha_loadmore_params.current_page++;
bottomOffset = ( $( '#main > div.post:last' ).offset() || {} ).top
}
}
});
}
});
});
functions.php - Added for further context
function misha_my_load_more_scripts() {
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js',
array( 'jquery' ), '', true );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
function misha_loadmore_ajax_handler() {
$args = json_decode( wp_unslash( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // load the next page
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'parts/content', get_post_format() );
endwhile;
endif;
wp_die();
}
add_action( 'wp_ajax_loadmore', 'misha_loadmore_ajax_handler' ); // Authenticated users
add_action( 'wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users
The trick here was to add the if statements inside of the AJAX handlers as well. Perhaps someone with AJAX experience can add to this one day to explain why it works, but all I know is that it does. All the code from my question is the same below is the difference from the functions.php ajax handler function.
function misha_loadmore_ajax_handler() {
$args = json_decode( wp_unslash( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // load the next page
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'parts/content', get_post_format() );
<?php if ($count == 2 && is_active_sidebar('sidebar1') ) : ?>
<div class="side-container first-side">
<?php dynamic_sidebar('sidebar1'); ?>
</div>
<?php endif; ?>
<?php if ($count == 10 && is_active_sidebar('sidebar2') ) : ?>
<div class="side-container first-side">
<?php dynamic_sidebar('sidebar2'); ?>
</div>
<?php endif; ?>
<?php if ($count == 20 && is_active_sidebar('sidebar3') ) : ?>
<div class="side-container third-side">
<?php dynamic_sidebar('sidebar3'); ?>
</div>
<?php endif;
endwhile;
endif;
wp_die();
}
This is my code which generates locations:
<select name="filter-location" id="location">
<option value="">
<?php if ( $input_titles == 'placeholders' ) : ?>
<?php echo __( 'Location', 'realia' ); ?>
<?php else: ?>
<?php echo __( 'All locations', 'realia' ); ?>
<?php endif; ?>
</option>
<?php
$locations = get_terms('locations', array(
'hide_empty' => false,
'parent' => 0
));
?>
<?php if ( is_array( $locations ) ) : ?>
<?php foreach ( $locations as $location ) : ?>
<option value="
<?php echo esc_attr( $location->term_id ); ?>"
<?php if ( ! empty( $_GET['filter-location'] ) && $_GET['filter-location'] == $location->term_id ) : ?>selected="selected"
<?php endif; ?>>
<?php echo esc_html( $location->name ); ?>
</option>
<?php endforeach; ?>
<?php endif; ?>
</select>
And this is the code which generates districts:
<?php $sublocations = get_terms('locations', array(
'hide_empty' => false,
'parent' => $location->term_id,
));
?>
As you can see, to generate districts, it needs $location->term_id.
How can I send $location->term_id whenever someone selects a location?
On changing the location selection, the ajaxDistrictsRequest() function is called with the selected value passed as a parameter.
<select name="filter-location" id="location" onchange="ajaxDistrictsRequest(this.value)">
<option value="">
<?php
if ( $input_titles == 'placeholders' ) :
echo __( 'Location', 'realia' );
else:
echo __( 'All locations', 'realia' );
endif;
?>
</option>
<?php
$locations = get_terms('locations', array(
'hide_empty' => false,
'parent' => 0
));
if ( is_array( $locations ) ) :
foreach ( $locations as $location ) :
$selected = ((! empty( $_GET['filter-location'] ) && $_GET['filter-location'] == $location->term_id ) ? "selected" : "";
?>
<option value="<?php echo esc_attr( $location->term_id ); ?>"
<?php echo $selected ?>><?php echo esc_html( $location->name ); ?></option>
<?php
endforeach;
endif;
?>
</select>
<select name="filter-sub-location" id="district" disabled>
<option value="">
</select>
The following code uses jQuery to send an AJAX request to districts.php with the provided value as term_id.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js">
<script type="text/javascript">
function ajaxDistrictsRequest(value) {
if (value) {
var districtSelect = document.getElementById('district');
// disable the #district list until it is populated by the response
districtSelect.disabled = true;
// make the ajax call to districts.php
$.ajax({
url: 'districts.php',
type: 'POST',
data: {
term_id : value
},
success: function (response) {
// populate the #districts option list with the result
districtSelect.innerHTML = response;
// enable the #district control
districtSelect.disabled = false;
}
});
}
});
</script>
For completeness here is a sample districts.php file which generates the options for the #district dropdown list:
<?php
if ( isset( $_POST['term_id'] ) ) :
$term_id = $_POST['term_id'];
// do database query
$sql = 'SELECT id, name FROM some_table WHERE term_id = :value';
$stmt = $dbh->prepare($sql);
$stmt->execute( array( ':value' => $term_id ) );
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) :
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
endforeach;
exit;
endif;
?>
I have only the first select up and running. Need help for the second. Can it be done only with PHP or it requires javascript or ajax? I'm using Wordpress btw.
function sellers_area_selection()
{
$args = array(
'post_type' => 'seller',
'taxonomy' => 'nomos',
'hide_empty'=> 0,
'parent' => 0
);
$categories = get_categories( $args );
if ( $categories ) {
echo '<select id="nomoi-select">';
echo '<option selected="" disabled="" value="0"><span>Νομοί</span></option>';
foreach ($categories as $category) {
$id = $category->term_id;
$name = $category->name;
echo '<option class="nomos" id="'. $id .'">'. $name .'</option>';
}
echo '</select>';
}
}
I'm trying to add a "load more" button and limit the results below, so that there aren't 1000 things loading all at once in the portfolio page, here: http://typesetdesign.com/portfolio/
My knowledge of PHP isn't very good, so I'm not sure what I'm supposed to do. I know I could limit the projects here:
<?php query_posts( 'post_type=project&posts_per_page=200' );
But how would I then load more if I limited that result?
Here is the page coding for that entire page:
<div id="projects" class="clearfix">
<?php $page_skills = get_post_meta($post->ID, "_ttrust_page_skills", true); ?>
<?php if ($page_skills) : // if there are a limited number of skills set ?>
<?php $skill_slugs = ""; $skills = explode(",", $page_skills); ?>
<?php if (sizeof($skills) > 1) : // if there is more than one skill, show the filter nav?>
<ul id="filterNav" class="clearfix">
<li class="allBtn"><?php _e('All', 'themetrust'); ?></li>
<?php
$j=1;
foreach ($skills as $skill) {
$skill = get_term_by( 'slug', trim(htmlentities($skill)), 'skill');
if($skill) {
$skill_slug = $skill->slug;
$skill_slugs .= $skill_slug . ",";
$a = '<li><a href="#" data-filter=".'.$skill_slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
}?>
</ul>
<?php $skill_slugs = substr($skill_slugs, 0, strlen($skill_slugs)-1); ?>
<?php else: ?>
<?php $skill = $skills[0]; ?>
<?php $s = get_term_by( 'name', trim(htmlentities($skill)), 'skill'); ?>
<?php if($s) { $skill_slugs = $s->slug; } ?>
<?php endif;
$temp_post = $post;
$args = array(
'ignore_sticky_posts' => 1,
'posts_per_page' => 200,
'post_type' => 'project',
'skill' => $skill_slugs
);
$projects = new WP_Query( $args );
else : // if not, use all the skills ?>
<ul id="filterNav" class="clearfix">
<li class="allBtn"><?php _e('All', 'themetrust'); ?></li>
<?php $j=1;
$skills = get_terms('skill');
foreach ($skills as $skill) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}?>
</ul>
<?php
$temp_post = $post;
$args = array(
'ignore_sticky_posts' => 1,
'posts_per_page' => 200,
'post_type' => 'project'
);
$projects = new WP_Query( $args );
endif; ?>
<div class="thumbs masonry">
<?php while ($projects->have_posts()) : $projects->the_post(); ?>
<?php
global $p;
$p = "";
$skills = get_the_terms( $post->ID, 'skill');
if ($skills) {
foreach ($skills as $skill) {
$p .= $skill->slug . " ";
}
}
?>
<?php get_template_part( 'part-project-thumb'); ?>
<?php endwhile; ?>
<?php $post = $temp_post; ?>
</div>
Thanks so much, any input is a help!
Edit
Using Tables with pagination bootstrap style http://datatables.net/examples/basic_init/multiple_tables.html
Massive data base with pagination take a look here: https://stackoverflow.com/a/3707457/2293454
I didn't see your site, now I have, what you might need is something like this:
https://stackoverflow.com/a/21408418/2293454
as you can see that example has a limiter iMyLoadLimit = 5, so, wen the user scroll down the page, it will load more based on the total number of fetched data, if you load 100 articles or 1000, they will be divided by the limiter in the java, the result will be that every time the user scroll down it will display the next 5 or whatever number you want to display...
I hope that helps...
You need pagination (server side) and might want infinite scrolling (client side)
You may want to look at:
Simple PHP Pagination script
http://jscroll.com/
How to paginate query results for Infinite Scroll?