How can I increment CPT title and slug reliably? - php

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

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 to update a category after update a post in WordPress?

I have a custom post type named Beaches. A category is created every time a post is created, this is working.
My category has the same title and the same slug as the post type.
The problem is when a post is updated, I can't link the post to the category anymore, if the title and the slug changes.
This code works to create a category:
function rci_custom_dynamic_beach_category ($post_id) {
$post = get_post($post_id);
if($post->post_status === 'auto-draft') return;
if($post->post_type !== 'beaches') return;
// Verify if the category exists already
$exist = term_exists($post->post_name, 'beaches');
if($exist !== 0 && $exist !== null) {
// THE PROBLEM IS HERE
// Get the category by the slug field
$term = get_term_by('slug', $post->post_name, 'beaches');
wp_update_term($term->term_id, 'beaches', array(
'name' => $post->post_title,
'slug' => $post->post_name
));
}
else {
wp_insert_term($post->post_title, 'beaches', $args = array(
'slug' => $post->post_name,
'parent' => 'houses'
));
}
}
add_action('save_post', 'rci_custom_dynamic_beach_category');
Is there a way to get the old slug value in order to find the term before the post update with the new values?

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;

Rewrite Wordpress url in CUSTOM POST TYPE

I have horoscope post type, where I have 4 categories (yearly, monthly, lovely and weekly horoscope) every post have 12 editors - 12 signs.
I need that URL structure:
In Yearly I need this url: http://domain.com/post-type/taxonomy/year
In Monthly I need this url:
http://domain.com/post-type/taxonomy/month/year
In Lovely I need this url:
http://domain.com/post-type/taxonomy/month/year
In Weekly I need this url: http://domain.com/post-type/taxonomy
In Yearly I have many years, in monthly and lovely I have many years and many month, in weekly just on page that edit every week.
At first I think that "taxonomy" - it will be parent category of taxonomy, "month" - it will be child category of taxonomy and "year" - it will be post.
But when create in on taxonomy the same name of category their slug became "month-1, month-2" and the same when I create the same post name in post type.
So this solution doesn't work.
Now I want to create 4 post type and in each post type rewrite url, like that:
In Yearly I need that in url show:
http://domain.com/horoscope/post-type/year-of-post create and no slug of post
In Monthly and Lovely I need that in url show:
http://domain.com/horoscope/post-type/month-of-post-create/year-of-post-create/ and no slug of post
In weekly just: http://domain.com/horoscope/weekly/
Now I create 4 post type and rewrite url with this code:
global $wp_rewrite;
$kuukausihoroskooppi_structure = '/horoskoopit/kuukausihoroskooppi/%monthnum%/%year%/%kuukausihoroskooppi%';
$wp_rewrite->add_rewrite_tag("%kuukausihoroskooppi%", '([^/]+)', "kuukausihoroskooppi=");
$wp_rewrite->add_permastruct('kuukausihoroskooppi', $kuukausihoroskooppi_structure, false);
// Add filter to plugin init function
add_filter('post_type_link', 'kuukausihoroskooppi_permalink', 10, 3);
// Adapted from get_permalink function in wp-includes/link-template.php
function kuukausihoroskooppi_permalink($permalink, $post_id, $leavename) {
$post = get_post($post_id);
$rewritecode = array(
'%year%',
'%monthnum%',
'%day%',
'%hour%',
'%minute%',
'%second%',
$leavename? '' : '%postname%',
'%post_id%',
'%category%',
'%author%',
$leavename? '' : '%pagename%',
);
if ( '' != $permalink && !in_array($post->post_status, array('draft', 'pending', 'auto-draft')) ) {
$unixtime = strtotime($post->post_date);
$category = '';
if ( strpos($permalink, '%category%') !== false ) {
$cats = get_the_category($post->ID);
if ( $cats ) {
usort($cats, '_usort_terms_by_ID'); // order by ID
$category = $cats[0]->slug;
if ( $parent = $cats[0]->parent )
$category = get_category_parents($parent, false, '/', true) . $category;
}
// show default category in permalinks, without
// having to assign it explicitly
if ( empty($category) ) {
$default_category = get_category( get_option( 'default_category' ) );
$category = is_wp_error( $default_category ) ? '' : $default_category->slug;
}
}
$author = '';
if ( strpos($permalink, '%author%') !== false ) {
$authordata = get_userdata($post->post_author);
$author = $authordata->user_nicename;
}
$date = explode(" ",date_i18n('Y F d H i s', $unixtime));
$rewritereplace =
array(
$date[0],
$date[1],
$date[2],
$date[3],
$date[4],
$date[5],
$post->post_name,
$post->ID,
$category,
$author,
$post->post_name,
);
$permalink = str_replace($rewritecode, $rewritereplace, $permalink);
} else { // if they're not using the fancy permalink option
}
return $permalink;
}
For Yearly post type I don`t need %monthum% in my url so in that post type in code:
$kuukausihoroskooppi_structure = '/horoskoopit/kuukausihoroskooppi/%monthnum%/%year%/%kuukausihoroskooppi%';
I remove %month%/ and this post type work good with url http://domain.com/horoscope/post_type/year_of_post/post_slug with template: single-post_type.php
But I don`t need post-slug, so I remove %kuukausihoroskooppi%, but then this page show like archive.php;
But post type Monthly and Lovely wich url with %monthum% is redirect to 404 page and dont show.
What better to do?

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