Using WP_Query within Plugin - wordpress

Im currently trying to adjust a Content SlideShow Plugin for Wordpress in order to make it compatible with WPML (Multilingual-Plugin). To achieve this, I simply need to fetch the posts from a specific category, put them into an array and return that array. WP_Query gives me a hard time doing this, as it seems like it's fetching the latest post infinite times in the loop. I'm not experienced in writing Wordpress Plugins, so I would be thankful for any hint you can give me.
This is the code of the plugins class method I'm trying to adjust.
function get_valid_posts(){
$validPosts = array();
$this_post = array();
$id_pot = array();
$my_query = new WP_Query('cat=15&showposts=10');
if($my_query->have_posts()) {
while ($my_query->have_posts()) :
$post = $my_query->post;
if(!in_array($post->ID, $id_pot)){
$this_post['id'] = $post->ID;
$this_post['post_content'] = $post->post_content;
$this_post['post_title'] = $post->post_title;
$this_post['guid'] = $post->guid;
array_push($id_pot, $post->ID);
array_push($validPosts, $this_post);
}
endwhile;
}
return $validPosts;
}
Note that I've added the $id_pot array in order to filter duplicate entries, but this shouldn't be necessary if the query / loop would work.
Thanks in advance!

I've managed to solve the problem:
function get_valid_posts(){
$validPosts = array();
$this_post = array();
$id_pot = array();
$i = 0;
$my_query = new WP_Query('category_name=gallery-post&showposts=10');
if($my_query->have_posts()) {
while($i < $my_query->post_count) :
$post = $my_query->posts;
if(!in_array($post[$i]->ID, $id_pot)){
$this_post['id'] = $post[$i]->ID;
$this_post['post_content'] = $post[$i]->post_content;
$this_post['post_title'] = $post[$i]->post_title;
$this_post['guid'] = $post[$i]->guid;
$id_pot[] = $post[$i]->ID;
array_push($validPosts, $this_post);
}
$post = '';
$i++;
endwhile;
}
return $validPosts;
}
$my_query->post returns the data of a specific post. Instead I had to use $my_query->post*s* to get an array with all the posts fetched as an object.

You are missing a call to the function the_post();:
while ($my_query->have_posts()) :
$my_query->the_post();
$post = $my_query->post;
// ...
endwhile;
See The WordPress Loop

Related

Moved my wordpress install to a subfolder and now the pagination doesn't work anymore?

So I moved a wp install to a subfolder and now the pagination for news section doensn't work anymore (trying out on a local xampp ). I already tried to update and resave the permalinks.
Is there any general code by which I can check if /news/page/3/ returns new data?
This is the longwave theme part in Template Name: Blog
//Post ID
global $wp_query;
$content_array = $wp_query->get_queried_object();
if(isset($content_array->ID)){
$post_id = $content_array->ID;
}
else $post_id=0;
$template_uri = get_template_directory_uri();
//Page Options
if(have_posts()) $pageoptions = getOptions($post_id);
//Theme Options
$themeoptions = getThemeOptions();
//Page Head Area
if(isset($pageoptions['tb_longwave_activate_page_title'])){
$headline = false;
}
else {
$headline = true;
}
//Default Values
$align = "";
//Orientation
if(empty($pageoptions["tb_longwave_blog_display_type"])) $pageoptions["tb_longwave_blog_display_type"]="left";
//Posts per Page
//Default Setting WP
$posts_per_page = get_option('posts_per_page');
//Optional Setting Page Options
if(!empty($pageoptions["tb_longwave_posts_per_page"]))
$posts_per_page = trim($pageoptions["tb_longwave_posts_per_page"]);
and the pagination nav part
if(have_posts()) :
//Postcounter is for Linebreaks + Display
$postcounter = 1;
while(have_posts()) : the_post();
//Custom Blog WP Query
if(!is_front_page())
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
else
$paged = (get_query_var('page')) ? get_query_var('page') : 1;
$args = array('offset'=> 0, 'paged'=>$paged, 'posts_per_page'=>$posts_per_page);
$all_posts = new WP_Query($args);
I also tried hardcoded
$args = array('offset'=> 0, 'paged'=>2, 'posts_per_page'=>8);
$all_posts = new WP_Query($args);
EDIT
Ok I found this code to work:
$all_posts = new WP_Query('showwposts='.$posts_per_page.'&paged='.$paged);//<--this work
// $all_posts = new WP_Query($args);//<-- this does not work
To move wordpress follow this guide : https://codex.wordpress.org/Moving_WordPress
Maybe you have to made changes in your database.
Just use this script https://interconnectit.com/products/search-and-replace-for-wordpress-databases/ and replace all localhost to yourdomain.tld in your database.
Use the script that Codeartist provided or WP Migrate DB plugin because there can be broken links or serialized data. WP Migrate DB handles serialized data.

Counting the while result at Wordpress

I have this featured listing and the code needs to count how many active featured listings the user has. I can't make the while loop work here in Wordpress. Here's code I used:
global $paged, $wp_query, $wp;
$args = wp_parse_args($wp->matched_query);
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query('post_type=post&posts_per_page=-1&author='.$user_ID);
$FeaturedAdsCount = 0;
while ($wp_query->have_posts()) : $wp_query->the_post();
$featured_post = "0";
$post_price_plan_activation_date = get_post_meta($post->ID, 'post_price_plan_activation_date', true);
$post_price_plan_expiration_date = get_post_meta($post->ID, 'post_price_plan_expiration_date', true);
$todayDate = strtotime(date('d/m/Y H:i:s'));
$expireDate = strtotime($post_price_plan_expiration_date);
if(!empty($post_price_plan_activation_date)) {
if(($todayDate < $expireDate) or empty($post_price_plan_expiration_date)) {
$featured_post = "1";
}
}
if($featured_post == "1") { $FeaturedAdsCount++; }
endwhile;
$wp_query = null; $wp_query = $temp;
echo $FeaturedAdsCount;
The output of $FeaturedAdsCount is always zero no matter if the user has active featured listing. Am I missing something here? Sorry I am still learning in PHP, self-taught actually. :) Thank you in advance!
PS: This is the postmeta table:
Okay! After hours of reading and googling, it says that when calling get_post_meta inside a loop, always use get_the_id() instead of $wp_query->post->ID or $post->ID. So the final get_post_meta must be like this to get a result inside a loop:
$post_price_plan_activation_date = get_post_meta(get_the_id(), 'post_price_plan_activation_date', true);
$post_price_plan_expiration_date = get_post_meta(get_the_id(), 'post_price_plan_expiration_date', true);
Thank you xphan for all the advice! :)

Function returning null in save post

I have a function that returns an array for me to dynamically populate the names of inputs of a post type. So I have this array and make a loop to generate the inputs.
This function is returning the array normally in other places, but in function that I use save_post always returns NULL. So, I can not get the names to save the values ​​with update_post_meta.
Why this function returns NULL in the function that I use save_post and other returns values ​​normally?
Could anyone help?
Thanks ...
function retornaPresencas() {
$post_id = $_GET['post'];
if (is_null($post_id)) :
return;
else:
$datas_turma = array(); $presenca_to_check = array();
$turma_da_lista = get_field("turma_lista", $post_id);
$args = array( 'post_type' => "turmas", 'p' => $turma_da_lista );
$query_turma_lista = new WP_Query( $args );
if ($query_turma_lista->have_posts()) : while ($query_turma_lista->have_posts()) : $query_turma_lista->the_post();
if(get_field('lista_de_dias_turma')) {
while(has_sub_field('lista_de_dias_turma')) {
$datas_turma[] = get_sub_field('dia_de_aula');
}
}
$lenght_datas_turma = count($datas_turma);
$alunos_turma = get_field('lista_de_alunos_turma');
foreach ($alunos_turma as $single_aluno) :
for ($i=0; $i < $lenght_datas_turma; $i++) :
$presenca_to_check[] = $single_aluno."_".$turma_da_lista."_".$datas_turma[$i];
endfor;
endforeach;
endwhile; endif; wp_reset_query();
endif;
return $presenca_to_check;
}
Saving a post in wordpress is a POST rather than a GET. When you attach a function to the save_post action, it is passed an argument containing the post ID. Amend your function to use the provided argument when called from save_post.
Remove the if/else statement and add $post_id as a function argument.
function retornaPresencas( $post_id ) {
$datas_turma = array(); $presenca_to_check = array();
...

wordpress pagination get current page number from url

I need to extract the value of "page" i.e 5 from this url - http://snypher.local/photos/page/5
What should I do to extract it in Wordpress? I am not able to get it from the $_GET super global.
use get_query_var example $page = get_query_var('paged'); in your case it's 5
its work fine i've tested on my current WP (version 3.5.1)
$current_page = max( 1, get_query_var('paged') );
$total_pages = $wp_query->max_num_pages;
echo 'Page '.$current_page.' of '.$total_pages;
Result = Page 3 of 51
function get_url_var($name)
{
$strURL = $_SERVER['REQUEST_URI'];
$arrVals = explode("/",$strURL);
$found = 0;
foreach ($arrVals as $index => $value)
{
if($value == $name) $found = $index;
}
$place = $found + 1;
return $arrVals[$place];
}
$page = get_url_var('page');
I have used this function to get the value of the variable page from the url.
Found a nice solution and I'd like to share it here for I was looking for exactly the same thing!
http://wordpress.org/support/topic/get-current-page-number-for-paginated-posts
So it's like:
<?php echo '(Page '.$page.' of '.$numpages.')'; ?>

WordPress: WP_Query in functions.php returns empty query (for a custom shortcode)

I'm writing a custom shortcode for a childtheme that I've dropped into my child themes functions.php. Here's the code:
function get_featured_video(){
$video_query = new WP_Query('category_name=videos&order=ASC');
$videoPath = "/";
$videoText = "";
while ($video_query->have_posts()){
$video_query->the_post();
$featured = get_post_meta($post->ID, "vid_feature", $single = true);
if(strtolower($featured)=='yes'){
$videoPath = get_permalink($post->ID);
$content = strip_tags($post->post_content);
$contentArr = str_word_count($content,1);
if(count($contentArr>50)){
$videoText = join(" ",array_slice($contentArr,0,50));
$videoText .= " <a href='$link'><read more></a>";
} else {
$videoText = $content;
}
break;
}
}
$returnStr = "<h1><a href='$videoPath'>You've Got to See This!</a></h1>\n";
$returnStr .= $videoText;
return $returnStr;
}
add_shortcode('getfeaturedvideo','get_featured_video');
The problem I'm having is that it's returning a blank query. I know there's a post in the videos category. I've never used the WP_Query inside functions.php. Is there a different method I need to use?
At the top of the function try declaring:
global $post;

Resources