change the final number of the permalink by +1 php - 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!

Related

WordPress replace all instances of [vc_single_image] shortcode with img src

im updating my WordPress website and removing the https://wpbakery.com/ editor and I'm wanting to remove the markup generated by the plugin.
This plugin https://codecanyon.net/item/shortcode-cleaner-clean-wordpress-content-from-broken-shortcodes/21253243 I'm using will remove all shortcodes with no problem except one. It's removing images.
On closer inspection images are posted on the backend using the below shortcode
[vc_single_image image="10879" img_size="large" add_caption="yes" alignment="center"]
And I want to update all references to use HTML instead
<img src="IMGURL">
However, I'm not sure about the right way to do it, any advice, please?
There is a regular expression replace in MySQL 8, but if you don't have that, you could do it with PHP.
$query = new WP_Query( [-- whatever posts you want--] );
while ( $query->have_posts() ) {
$query->the_post();
$content = get_the_content();
preg_match('/\[vc_single_image image="(\d+)" img_size="(\w+)"[^\]]*\]/', $content, $matches);
if( isset($matches[1]) ) {
$url = wp_get_attachment_image_url( (int) $matches[1], $matches[2] );
$img = sprintf( '<img src="%s" />', $url );
$new_content = str_replace( $matches[0], $img, $content );
wp_update_post( [ 'ID' => get_the_ID(), 'post_content' => $new_content] );
}
}
Here Is the updated answer to update all images in the post/page content. The above code finds the first image of the content and update that.
// Args for the WP_Query
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'post__in' => array(5824),
'orderby' => 'post__in'
);
// Execute WP_Query with args
$query = new WP_Query( $args );
// Start the Loop
while ( $query->have_posts() ) {
$query->the_post();
// Get Page/Post content
$content = apply_filters('the_content', $content);
// Get the vc_single_image count from the post
$found_keyword = substr_count( $content,"vc_single_image" );
// Start loop to replace all elements from the content
for ($i=0; $i < $found_keyword; $i++) {
// Get the position of vc_single_image shortcode with Image ID and Image Size
preg_match( '/\[vc_single_image image="(\d+)" img_size="(\w+)"[^\]]*\]/', $content, $matches );
// Check shotcode are exist on loop
if( isset( $matches[1]) ){
// Get the Image ur by Image id and Size
$url = wp_get_attachment_image_url( (int) $matches[1], $matches[2] );
$img = sprintf( '<img src="%s" />', $url );
// Replce shortcode with <img> tag
$content = str_replace( $matches[0], $img, $content );
}
}
// Update post content with updated content with <img> tag
wp_update_post( [ 'ID' => get_the_ID(), 'post_content' => $content] );
}
// END the Loop

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

Wordpress shortcode function

Can anyone explain why this only returns the 1st result only. I want to return all results that have the same custom field value as the current url. It will ony return 1. Does it need a for each or something? Thank you!!
<?php add_shortcode( 'feed', 'display_custom_post_type' );
function display_custom_post_type(){
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$args = array(
'post_type' => 'custom_post_type',
'posts_per_page' => -1
);
$new_query = new WP_Query($args);
while($new_query->have_posts()) : $new_query->the_post();
return get_title();
endwhile;
};?>
Because you have added the return inside the loop it will only display the last one. You have to place the return outside the loop for it to display all.
Just a small example to see it work, change this bit:
while($new_query->have_posts()) : $new_query->the_post();
return get_title();
endwhile;
to this:
while($new_query->have_posts()) : $new_query->the_post();
$all_titles .= get_title();
endwhile;
return $all_titles;
It will most probably show all the titles in a single row, so just format as you wish!
You "return" from the function after the first element inside the while loop.
example returning all the posts:
$args = array(
'post_type' => 'custom_post_type',
'posts_per_page' => -1
);
$results = get_posts($args);
return $results;

Wordpress get_posts() fetch next batch of posts

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.

Auto Increment Custom Post Type Title

I created a custom post type "Testimonials" and removed support for the title. I am wanting to auto increment the title such as Testimony #1, Testimony #2, Testimony #3, etc.. right now it saves as "auto draft". Any help would be appreciated.
BTW I am not echoing the title, it will only be visible by me.
Made some improvements to the code provided #the-alpha.
// Use a filter to make the change
add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );
function modify_post_title( $data , $postarr ) {
// Check for the custom post type and if it's in trash
// We only need to modify if it when it's going to be published
$posts_status = ['publish', 'future', 'draft', 'pending', 'private', 'trash'];
if( $data['post_type'] == 'oferta' && !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('you custom post type');
$published_posts = $count_posts->publish;
// Check if it's the first one
if ($published_posts == 0) {
$data['post_title'] = date('Y-m') . '-1';
} else {
// Get the most recent post
$args = array(
'numberposts' => 1,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'you custom post type',
'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 = $number[2] + 1;
// Save the title.
$data['post_title'] = date('Y-m') . '-' . $number;
}
}
return $data;
}
In this case the user doesn't have the ability to modify the custom post type title and whole thing increments based on the title.
on post submission from frontend custom post title set to #1 but not increment to #2 on second post submission..
This is the exact code used in functions.php
add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );
function modify_post_title( $data , $postarr )
{
if( $data['post_type'] == 'your custom post type' ) {
$last_post = wp_get_recent_posts( '1');
$last__post_id = (int)$last_post['0']['ID'];
$data['post_title'] = 'Testimony #' . ($last__post_id+1);
}
return $data;
}

Categories