Wordpress get_posts() fetch next batch of posts - php

I'm using the get_posts() function to fetch a batch of posts from a custom post type, sorted by ID, modify those posts and then fetch the next batch.
I have the following code:
<?php
require_once('wp-load.php');
$temp_list_of_products_array = get_posts( array('post_type' => 'sale', 'numberposts' => 10 ) );
$temp_list_of_products_array_length = count( $temp_list_of_products_array );
for ($xt = 0; $xt < $temp_list_of_products_array_length; $xt++) {
$temp_product_id = $temp_list_of_products_array[$xt]->ID;
$temp_product_untranslated_field = get_post_meta($temp_product_id, 'wpcf-product-details', true);
$temp_product_translated_field = get_post_meta($temp_product_id, 'wpcf-translated-product-details', true);
$temp_product_description_language = 'en';
if ($temp_product_translated_field == null) {
$temp_product_translated_contents = google_translate_text($temp_product_untranslated_field, $temp_product_description_language);
update_post_meta($temp_product_id, 'wpcf-translated-product-details', $temp_product_translated_contents);
}
echo $temp_product_id;
}
?>
This works great but the problem is that it only loads the first 10 posts ordered by date.
My question is, how do I get the next batch of 10 posts without have a user activated pagination call?
Thanks

first get the current page
$paged=($query_vars['paged']!=0 ? $query_vars['paged'] : 1);
now calculate the offset value
$numberposts=10;
$ofdset=$numberposts* ($paged - 1) ;
add your code
$temp_list_of_products_array = get_posts( array('post_type' => 'sale', 'numberposts' => 10 ,'offset'=>$offset) );
$temp_list_of_products_array_length = count( $temp_list_of_products_array );
for ($xt = 0; $xt < $temp_list_of_products_array_length; $xt++) {
$temp_product_id = $temp_list_of_products_array[$xt]->ID;
$temp_product_untranslated_field = get_post_meta($temp_product_id, 'wpcf-product-details', true);
$temp_product_translated_field = get_post_meta($temp_product_id, 'wpcf-translated-product-details', true);
$temp_product_description_language = 'en';
if ($temp_product_translated_field == null) {
$temp_product_translated_contents = google_translate_text($temp_product_untranslated_field, $temp_product_description_language);
update_post_meta($temp_product_id, 'wpcf-translated-product-details', $temp_product_translated_contents);
}
echo $temp_product_id;
}
add pagination code at bottom of loop
check this for wordpress pagination with get_posts function
https://wordpress.stackexchange.com/questions/137100/using-pagination-with-get-posts-on-page-type

You can simply use the paged parameter:
$current_page = 1; // <-- Modify this to your needs!
$temp_list_of_products_array = get_posts(
array(
'paged' => $current_page,
'post_type' => 'sale',
'posts_per_page' => 10
)
);
for paging.

Related

change the final number of the permalink by +1 php

these days I wonder how I can change the final permalink number of my posts by +1, i found this code on the net, but it needs to be changed someone help me?
// Get all posts
$query = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => -1,
));
$posts = $query->get_posts();
foreach ($posts as $post) {
// Get permalink
$url = $post->post_name;
// old url
$old_url = array(
'http://localhost:8888/site/testpermalink-1/',
'http://localhost:8888/site/testpermalink-1/',
'http://localhost:8888/site/testpermalink-7/',
'http://localhost:8888/site/testpermalink-4/',
'http://localhost:8888/site/testpermalink-36/',
);
// Replacement
//$replacement = '';
// Replace url
//$new_url = str_replace($old_url, $replacement, $url);
// Prepare arguments
$args = array(
'ID' => $post->ID,
'post_name' => $new_url,
);
// Update post
wp_update_post( $args );
}
}
I would like this list to be changed with the final number +1, so this list after editing should be:
$new_url = array(
'http://localhost:8888/site/testpermalink-2/',
'http://localhost:8888/site/testpermalink-2/',
'http://localhost:8888/site/testpermalink-8/',
'http://localhost:8888/site/testpermalink-5/',
'http://localhost:8888/site/testpermalink-37/',
);
however then these permalink should be automatically saved after you change them.
Permalink is the post_name in database, sometimes called "slug".
You can do something similar:
foreach ($posts as $post) {
// split it into pieces, dividing by - character
$pieces = explode('-', $post->post_name);
//replace last piece adding 1
$pieces[array_key_last($pieces)] = (int)$pieces[array_key_last($pieces)] + 1;
//restore pieces
$post->post_name = implode('-', $pieces);
wp_update_post( $post );
}
WARNING: array_key_last function exists from PHP 7.0!

How can I increment CPT title and slug reliably?

I've got a custom post type called 'tasks' with an ACF front end to post each new one.
I'd like to hide the title from the end user, and have the title & slug automatically set & increment.
Task 1, Task 2, Task 3 etc.
I've tried all the code examples on here I can find & nothing seems to be reliable.
Has anyone got anything they've used in the past that works reliably?
Tried this;
add_filter('title_save_pre','auto_generate_post_title');
function auto_generate_post_title($title) {
global $post;
if (isset($post->ID)) {
if (empty($_POST['post_title']) && 'produktionsauftrag' == get_post_type($post->ID)){
// get the current post ID number
$id = get_the_ID();
// add ID number with order strong
$title = 'produktionsauftrag-'.$id;} }
return $title;
}
Just gives me a post with the title 'untitled' & the next post id as the slug
Tried this one
add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );
function modify_post_title( $data , $postarr ) {
// Check for the custom post type and it's status
// We only need to modify it when it's going to be published
$posts_status = ['publish', 'future', 'pending', 'private', 'trash'];
if( $data['post_type'] == 'task' && !in_array($data['post_status'], $posts_status)) {
// Count the number of posts to check if the current post is the first one
$count_posts = wp_count_posts('task');
$published_posts = $count_posts->publish;
// Check if it's the first one
if ($published_posts == 0) {
// Save the title and the slug
$data['post_title'] = date('Y-m') . '-1';
$data['post_name'] = sanitize_title($data['post_title']);
} else {
// Get the most recent post
$args = array(
'numberposts' => 1,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'task',
'post_status' => 'publish'
);
$last_post = wp_get_recent_posts($args);
// Get the title
$last_post_title = $last_post['0']['post_title'];
// Get the title and get the number from it.
// We increment from that number
$number = explode('-', $last_post_title);
$number = intval($number[2]) + 1;
// Save the title and the slug
$data['post_title'] = date('Y-m') . '-' . $number;
$data['post_name'] = sanitize_title($data['post_title']);
}
}
return $data;
}
Does nothing, acf form page just refreshes itself

Adding multiple options to PHP query

I have a property listing site and I need help with the code that filters search results. The code below includes all properties with the contract type "southern-oregon". I would like it to ALSO include contract types = to "medford-office". Can someone tell me how to add that to the code?
Here is the code:
<?php
echo $div; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(array('post_type'=>'property','post_status'=>'publish','paged'=>$paged,
'author'=>$agent, 'property-contract-type'=>'southern-oregon'));
if(have_posts()):while(have_posts()):the_post();
$property_images = get_post_meta(get_the_ID(),'imic_property_sights',false);
$total_images = count($property_images);
$property_term_type = '';
$property_area = get_post_meta(get_the_ID(),'imic_property_area',true);
$property_baths = get_post_meta(get_the_ID(),'imic_property_baths',true);
$property_beds = get_post_meta(get_the_ID(),'imic_property_beds',true);
$property_parking = get_post_meta(get_the_ID(),'imic_property_parking',true);
$property_address = get_post_meta(get_the_ID(),'imic_property_site_address',true);
$property_city = get_post_meta(get_the_ID(),'imic_property_site_city',true);
$property_price = get_post_meta(get_the_ID(),'imic_property_price',true);
$contract = wp_get_object_terms( get_the_ID(), 'property-contract-type',
array('fields'=>'ids'));
$property_id = get_post_meta(get_the_ID(),'imic_property_site_id',true);
$property_area_location = wp_get_object_terms(get_the_ID(), 'city-type');
$sl = '';
$total_area_location = count($property_area_location);
$num = 1;
foreach($property_area_location as $sa) {
$conc = ($num!=$total_area_location)?'->':'';
$sl .= $sa->name.$conc; $num++;
}
// We get Longitude & Latitude By Property Address
$property_longitude_and_latitude=get_post_meta(get_the_ID(),'imic_lat_long',true);
if(!empty($property_longitude_and_latitude)){
$property_longitude_and_latitude = explode(',',
$property_longitude_and_latitude);
}else{
$property_longitude_and_latitude=getLongitudeLatitudeByAddress($property_address);
}
global $imic_options;
$currency_symbol = imic_get_currency_symbol($imic_options['currency-select']);
$src = wp_get_attachment_image_src(get_post_thumbnail_id(),'150-100-size');
if(!empty($src)):
$image_container= '<span class ="property_image_map">'.$src[0].'</span>';
else:
$image_container='';
endif;
if(!empty($contract)) {
$term = get_term( $contract[0], 'property-contract-type'); $property_term_type = $term->name;
}
if($design_type=='listing') {
?>
I expect this is the core of your filtering system (significantly reformatted for readability - ask your developer to fix this please):
query_posts(
array(
'post_type' => 'property',
'post_status' => 'publish',
'paged' => $paged,
'author' => $agent,
'property-contract-type' => 'southern-oregon'
)
);
At a guess, try replacing 'southern-oregon' with an array, thus:
['southern-oregon', 'medford-office', ]
I would guess this would do an IN, which is essentially an OR.

Wordpress, random product only on home search page

I have a custom wordpress search page with page navigation numbers, my client asks me to random products on page 1 but not for others, but all products displayed randomly on home page should not displayed on others pages.
For the query i have this code :
$args = array(
'post_type' => 'products',
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 )
)
and for the random :
if( $args['paged'] == 1) {
$args['orderby'] = 'rand';
} else {
$args['order'] = 'DESC':
}
the results are there when i do a search, and first page random well, but some products that are already displayed on home page because of the random are also displayed on others pages (ex : page 2 ).
The aim is not display products that are already displayed on home page.
I already do something similar :
if( $page == 1 ) shuffle($r->posts);
But it shuffle only first the 10 products on page 1, and others products on others pages never display on page 1.
After some thoughts i think store first 10 random products to cookie or session and do a NOT IN for others pages ? like this ?
if( $args['paged'] == 1 ){
$args['orderby'] = 'rand';
$r = new Wp_Query($args);
$randomFirstPage = wp_list_pluck( $r->posts, 'ID' );
print_r($randomFirstPage);
setcookie( 'firstPageResults', $randomFirstPage, time()+3600, '/', 'mydomain.com/dev' );
}else{
$not_in = $_COOKIE['firstPageResults'];
$args['NOT IN'] = $not_in;
$r = new Wp_Query($args);
}
Sorry for bad english, and may you help me please ?
Thanks
Try this aproach:
<?php
$products1_ids = array();
$products2_ids = array();
$allproducts = get_posts(array('post_type' => 'products'));
$p=1; foreach($allproducts as $products) {
if(is_page(1) && $p<11) {
$products1_ids[] = $products->ID;
}
if(!is_page(1) && $p>10) {
$products1_ids[] = $products->ID;
}
$p++; }
shuffle($products1_ids);
shuffle($products2_ids);
$post_in = is_page(1) ? $products1_ids : $products2_ids;
$products = new WP_Query(array(
'post_type' => 'products',
'posts_per_page' => 10,
'post__in' => $post_in,
));
if($products->have_posts()) {
while($products->have_posts()) { $products->the_post();
echo '<div class="post">'
the_title();
echo '</div>';
}
}
Hope it helps
Your posted code above uses $args['NOT IN'] = $not_in;, but according to the WP_Query docs the argument to exclude posts by id is post__not_in:
$query = new WP_Query(
array('post_type' => 'post', 'post__not_in' => array(2, 5, 12, 14, 20))
);
So try:
$args['post__not_in'] = $not_in;

Insert a post type every x posts in custom loop

I was hoping someone could help me with this problem.
I'm trying to make a loop in wordpress with two different post types ('product' and 'outfits')
The code below is working fine, this outputs a list of the two post types ordered by newest to older.
$loop = new WP_Query( array(
'post_type' => array( 'product', 'outfits' ),
'posts_per_page' => 15
) );
$counter = 0;
?>
<?php if ( $loop->have_posts() ) { while ( $loop->have_posts() ) { $loop->the_post();
$counter++; ?>
<?php $loop->is_home = false; ?>
<?php
$large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'large');
$titulo = get_the_title();
$content = apply_filters ('the_content', $post->post_content); ?>
<div class="caja-<?php echo $counter; ?>">
<?php if ( $post->post_type == "product" ) {
//some stuff
<?php } else {
//some stuff
} ?>
</div>
<?php } } wp_reset_postdata();
What I would like to do is to insert a product post type after X number of outfits.
I was trying to merge a similar solution I've found in other question with no luck. I'm not a php expert so any help is appreciated
<?php
$args = array('post_type'=>'post', 'posts_per_page'=>9, 'category_name'=>'news');
$posts = get_posts($args);
$args = array('post_type'=>'testimonials', 'posts_per_page'=>3);
$testimonials = get_posts($args);
// see how many of the regular posts you got back //
$post_count = count($posts);
// see how many testimonials you got back //
$testimonial_count = count($testimonials);
// add them up to get the total result count //
$total_count = $post_count + $testimonial_count;
// Loop through the total number of results //
for($i = 1; $i <= $total_count; $i++){
// assuming you want to show one testimonial every third post //
if($i % 3 == 0){
// this means you're on the a third post, show a testimonial //
setup_postdata($testimonials[$i]);
}
else{
/** show a regular post */
setup_postdata($posts[$i]);
}
/** and now handle the output */
?><h1><?php the_title();?></h1><?php
} ?>
$x = 3;
$products = get_posts(array(
'post_type' => 'product',
'posts_per_page' => -1
));
$outfits = get_posts(array(
'post_type' => 'outfit',
'posts_per_page' => -1
));
foreach ($outfits as $num => $outfit) {
if ( ($num+1) % $x == 0) {
if (isset($products[($num+1)/$x - 1])) {
array_splice( $outfits, $num, 0, array($products[($num+1)/$x - 1]) );
}
}
}
foreach ($outfits as $outfit) {
$posts_id[] = $outfit->ID;
}
$query = new wp_query(array(
'post_type' => array('outfit', 'product'),
'post__in' => $posts_id,
'posts_per_page' => 15,
'orderby' => 'post__in'
));

Categories