How to refresh pagination links after submit new query? - wordpress

I modified WordPress main loop for blog posts, made it query and loop through different types of posts according to what filter is submitted.
At the beginning of the HTML, there is a form with several buttons as option, it's similar to the SA site menu: Questions Tags Users Badges Unanswered.
When visitor click one of the menu button, a new WP_Query is submitted.
Below the options, is the loop of posts, depends on what filter is submitted.
The php codes is basically a standard wordpress loop with customized functions:
$args= !empty($_POST['filter']) ? $_POST['filter']:null;
get_option_nav();
if( my_loop_have_posts(array('filter'=>$args))):
while my_loop_posts(): the_my_loop_post();
get_template_part('contents');
endwhile;
endif;
Things are working fine except that only the default filter get the correct pagination links. After submit a new filter, when click the pagination links, it goes to the default filter's pages. How to modify wordpress pagination links to get it work for the other filters?
Here's the code that I use for query args:
function get_args($args){
$defaults= array(
'order' => 'DESC',
'orderby' => 'modified',
'max_num_pages' =>5,
'paged' => get_paged (),
'post_status' => 'any',
'post_type' => array ('post', 'docs','topics'),
'posts_per_page' => 5,
)
$args = wp_parse_args ( $args, $defaults );
extract ( $args );
if(!empty($args['filter'])){
switch ($args['filter']){
case 'top_voted':
$args['post_type'] = 'docs';
$args['meta_key'] = '_vote_total';
$args['order'] = 'DESC';
$args['orderby']='meta_value_num';
break;
case 'unanswered_questions':
$args['post_type] = 'topics';
$args['blabla'] = 'blabla';
break;
default:
blabla;
break;
}
return $args;
}
and the code for the paged:
function get_paged() {
global $wp_query;
if ( get_query_var( 'paged' ) ) {
$paged = get_query_var( 'paged' );
} elseif ( ! empty( $wp_query->query['paged'] ) ) {
$paged = $wp_query->query['paged'];
}
if ( ! empty( $paged ) )
return (int) $paged;
return 1;
}

When you make a custom query, you need to explicitly call every parameter of the query. Thus, standard ones disappear, as is the pagination case.
Depending on how you are making this new query you could try:
To concatenate at the beginning $query_string, for example
$query = new WP_Query( $query_string . 'order=DESC' ) As it is explained in the Codex:
If you want to preserve the original query parameter information that
was used to generate the current query, and then add or over-ride some
parameters, you can use the $query_string global variable in the call
to query_posts().
To get the pagination from the default query and use it in your custom query
$paged = get_query_var('paged'); $query = new WP_Query( array( 'paged' => $paged ) );
In your case there is something wrong with your get_paged() function. I have tested it and it does not work, but I have not found the bug. Instead, I tried what I usually use, and it works for me:
function get_paged() {
if ( get_query_var('paged') ) {
$paged = get_query_var('paged');
} elseif ( get_query_var('page') ) { $paged = get_query_var('page');
} else { $paged = 1; }
return $paged;
}
Something seems to fail in you else if statement. Let me know if this solves your issue.

Related

Fetch contact-form-7 id to another plugin

How to fetch contact-form-7 forms ID, to another plugin??
I want to get forms id and using that id, ill give some effect to that form, please tell me how to fetch form id from contact-form-7, to another plugin in wordpress.
Actually in contact form 7,the post type is wpcf7_contact_form
So you can use this bellow code . In tis code the function return an array of all contact form's id.
function get_cf7_IDS(){
$cf7_id_array =array();
if ( post_type_exists( 'wpcf7_contact_form' ) ) {
$args = array(
'post_type' => 'wpcf7_contact_form',
'posts_per_page'=>-1,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$cf7_id_array[]= get_the_ID();
}
wp_reset_postdata();
}
}
return $cf7_id_array; //RETURN THE ARRAY OF IDS
}
Then use this function to get all ides in array get_cf7_IDS().
Then let me know the result.
Thanks
Try below code. i hop it help you
$args = array('post_type' => 'wpcf7_contact_form', 'posts_per_page' => -1);
$cf7Forms = get_posts( $args );
foreach($cf7Forms as $f)
{
// Contact form id
echo $f->ID;
}

$wp_query and WP_QUERY - same arguments, different results

I spend this whole day trying to figure out a problem with a combination of a custom query and custom post types. This is my last resort...
The setting
I wrote a plugin that introduces some custom post types to my WordPress. To display them in the main query I hooked them into the query like this:
function add_cpt_to_query( $query ) {
*some code...*
// add custom post types to query
if ( !( is_admin() || is_post_type_archive() || is_page() ) && $query->is_main_query() ) {
$query->set('post_type', array_merge( array('post'), $cpt ) );
}
}
add_action('pre_get_posts','add_cpt_to_query');
In my theme on the other hand I setup ajax pagination like this:
function setup_pagination() {
global $wp_query;
$max_pages = $wp_query->max_num_pages;
$current_page = ( $wp_query->paged > 1 ) ? $wp_query->paged : 1;
$ajaxurl = admin_url( 'admin-ajax.php' );
wp_register_script( 'ajax-pagination', get_template_directory_uri() .'/js/dummy.js', array('jquery'), '', true);
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
'max_pages' => $max_pages,
'current_page' => $current_page,
'ajaxurl' => $ajaxurl,
'query_vars' => $wp_query->query_vars
));
wp_enqueue_script( 'ajax-pagination' );
}
add_action( 'wp_enqueue_scripts', 'setup_pagination' );
function pagination() {
$query = $_POST['query_vars'];
$query['paged'] = $_POST['next_page'];
/*
$query = array(
'paged' => 2,
'post_type' => array('post', 'custom_post_type_1', 'custom_post_type_2' )
);
*/
$posts = new WP_Query( $query );
$GLOBALS['wp_query'] = $posts;
// Start the loop.
while ( have_posts() ) : the_post();
?>
*some code...*
<?php endwhile;
die();
}
add_action( 'wp_ajax_nopriv_ajax_pagination', 'pagination' );
add_action( 'wp_ajax_ajax_pagination', 'pagination' );
and the script part:
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
next_page: parseInt(ajaxpagination.current_page) + 1
}
});
The problem
If I pass the query_vars array I get from $wp_query with the altered 'paged' value back to WP_QUERY, it returns the wrong set of posts. It looks like, that WP_QUERY does not account for the cpts in the loop. Though these cpts are mentioned in the 'post_type' of the query_vars array and thereby passed along to the new WP_QUERY.
When I manually set 'post_type' and only pass this argument, it works as intended. The aspect that blows my mind is, that the resulting query_vars used in the ajax call to WP_QUERY are exactly the same, but only when I manually set 'post_type' the pagination works as it should.
I dont know if this was a somewhat understandable explanation, but I'm thankful for every idea that could help me out. Big THX!
Ok... I got it now.
I made a mistake in wp_localize_script(). The query_vars should be a json-string, I on the other hand just passed the array itself. My code above has to be altered in two lines:
function mk_setup_pagination() {
...
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
...
'query_vars' => json_encode($wp_query->query_vars) <- convert to json-string
));
...
}
function mk_pagination() {
$query = json_decode( stripslashes( $_POST['query_vars'] ) , true); <- convert json-string to array
...
Works like a charm now. :)
btw: the code is based on a tutorial by wpmudev.org: Loading WordPress Posts Dynamically With AJAX

How do I search ACF (Advanced Custom Fields) data with the conditional logic?

All,
I'm running a search with Wordpress and it's returning ACF data. The problem, is that for fields that are hidden with conditional logic, they are still returning in the search results.
Does anyone happen to know how to exclude fields that are hidden? Or, does anyone know those items are declared as hidden in the database? I can't seem to find anything that ties a field to another in the wp_postmeta.
EDIT: added some code by request
<?php
error_reporting(0);
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
}
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$search = new WP_Query(
$search_query,
array(
'post_type' => 'page',
'post_status'=>'publish',
'post__in' => array(),
//'posts_per_page' => -1,
'paged' => $paged
)
);
$resultArray = array();
if (have_posts()){
while(have_posts()): the_post();
//places the WP post meta data into an array
$array = get_post_meta($post->ID);
//Flattens the array into one-dimensonal
$result = call_user_func_array('array_merge', $array);
//changes the search term to all lower case
$searchword = strtolower($search_query['s']);
//Searches the $result array for the $searchword and saves all occurances into $matches array
$matches = array_filter($result, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", strip_tags($var)); });
//Grab the first value of the $matches array since we won't always know the key
$first_value = reset($matches);
if(!empty($first_value)){
array_push($resultArray,
array(
'id'=>$post->ID,
'match' =>strip_tags($first_value)
)
);
}
endwhile;
}
$total_results = count($resultArray);
?>

Wordpress: Custom post type segregation on Category page

I've got two custom post types, for example 'Cars' and 'Bikes'. I've used Wordpress's default category to categorise the posts from the two post types. Let's say for example the categories are 'Red', 'Blue' and 'Black'.
What I'm trying to achieve here is that when I go to the category page for 'Red', I want to see the 'Cars' and the 'Bikes' that are categorised under 'Red'. I'm using the category.php and this is the query that I'm trying to run:
$car_args = array(
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'cars',
'post_status' => 'publish',
'cat' => $cat
);
// The Query
$car_query = new WP_Query( $car_args );
// The Loop
if ( $car_query ->have_posts() ) {
echo "<h3>Cars</h3>";
while ( $car_query->have_posts() ) {
$car_query->the_post();
echo get_post_type() . '' . get_the_title() . '<br />';
}
} else {
// no posts found
}
$bikes_args = array(
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'bikes',
'post_status' => 'publish',
'cat' => $cat
);
// The Query
$bikes_query = new WP_Query( $bikes_args );
// The Loop
if ( $bikes_query ->have_posts() ) {
echo "<h3>Bikes</h3>";
while ( $bikes_query->have_posts() ) {
$bikes_query->the_post();
echo get_post_type() . '' . get_the_title() . '<br />';
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
The $cat in the query gets the category id of 'Red' category. Both these queries are correctly restricting the posts by the 'Red' category but posts from both the 'Cars' post type and 'Bikes' post type are showing up even though I've tried to restrict by post type. I've read in a few articles that Wordpress ignores the post type args on the category page. Is this true and if it is, is there a workaround for this?
What you are trying to do is possible with one query only, and only with the main query without any custom queries.
First of all, lets first add your custom post types to your category page. By default, custom pist types are excluded from category pages. So we need to add this manually to the main query arguments via pre_get_posts. Add the following to your functions.php: (CAVEAT: Untested and also requires PHP 5.3+)
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() && $q->is_main_query() && $q->is_category() ) {
$q->set( 'post_type', array( 'post', 'cars', 'bikes' ) ); // Change this according to your post types
$q->set( 'nopaging', true ); // This will get all posts, same as posts_per_page=-1
}
});
You should now have all posts from a clicked category is your set post types on your category pages.
Next, wee need to sort out your loops. Delete all your custom queries in category.php and replace it with the default loop. As you would want two block ordered by post type, we will use rewind_posts() so we can run the loop twice
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
if ( $post->post_type == 'cars' ) { //Change accordingly to only show cars in this loop
// Your loop
}
}
rewind_posts();
while ( have_posts() ) {
the_post();
if ( $post->post_type == 'bikes' ) { // Change accordingly to only show bikes
// Your loop
}
}
}
This should now display your posts in two block sorted by post type

Filter wordpress query by checkboxes

I have a situation where I have a query with two different post types and I have to checkboxes on top with the names of post type. I wont by default those checkboxes to be checked and if one of theme is unchecked to remove that post type and the post affiliated to that post type from the query.
This part is circumstancial, but you get the idea. Give the values to the ones that are/aren't checked.
if($checkboxone == '1') {
$types = array( 'typeone' )
}
if($checkboxtwo == '1') {
$types = array( 'typetwo' )
}
if($checkboxtwo == '1' && $checkboxone == '1'){
$types = array( 'typeone', 'typetwo' )
}
then plug that value into your WP_Query by some means like this. the documentation for it is here
// The Query
$the_query = new WP_Query( array( 'post_type' => $types );
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
//DO STUFF
endwhile;
// Reset Post Data
wp_reset_postdata();

Resources