The problem: Due to RSS conversion to posts related issues, I want to have just one blog post published in the backend of the my blog page. I am aware that I can display only the last blog post but is not what I want.
Is there a function or a plugin that could delete/remove permanently all other posts that are already published every time I publish a post?
I found a solution. I hope it helps someone with the same question:
function delete_all_posts_less_the_first() {
$posts_less_the_first = get_posts( array( 'post_type' => 'post', 'offset' => '1') );
foreach ( $posts_less_the_first as $post_less_the_first ) {
// Delete all posts less the first.
wp_delete_post( $post_less_the_first->ID, true); // Set to False if you want to send them to Trash.
}
}
add_action( 'init', 'delete_all_posts_less_the_first' );
Related
How do I prioritize posts over pages in a wordpress/genesis search result page? Similar to this code, except I'd like posts to show before pages and I can't seem to fully adjust this code to do it:
function change_search_result_order($query) {
// Check if current page is search page
if ($query->is_search) {
// Specify orderby and order, ordering will be by slug of post_type: pAge > pOst
$query->set('orderby', 'post_type');
$query->set('order', 'ASC');
};
return $query;
}
add_filter('pre_get_posts', 'change_search_result_order');
this code block was also mentioned, but I can't seem to find where it fits--if I could, would it be as simple as switching page and post?
$query->set('post_type', array('page','post'));
Original source: How to prioritize pages over posts when searching?
thanks in advance!
Adam
If you break down the code that was given in that other answer, you can clearly see what it's doing.
The custom function is called on pre_get_posts, which is before any posts are fetched.
Inside the function, it makes sure it's a search query, and won't fire on other pages or page templates.
It sets the post_types to page and post, thereby removing any custom post types.
It changes the order of the post to order by the name of the post_type
It changes the order of the posts to be Ascending or Descending.
Add the post_types in there, so that way if you use another plugin that adds CPTs or add your own, they won't be included (such as events or staff members).
Since WP 4.0 the $query accepts type as an orderby parameter. Note that post_type works as well, but the default non-aliased value is type.
Change the order to Desc since you want [PO]sts before [PA]ges
add_filter( 'pre_get_posts', 'change_search_result_order' );
function change_search_result_order($query){
if( $query->is_search ){
$query->set( 'post_type', array( 'page', 'post' ) );
$query->set( 'orderby', 'type' );
$query->set( 'order', 'DESC' );
};
return $query;
}
Stick that in your functions.php file and you should be good to go.
I am developing this plugin that admin can add a user in the backend and when user is created, plugin can automatically generate one custom post which I have added to the theme. The custom post will store user ID that is just created (or if it is possible make that user an author of the post)
I wonder if what I have mentioned above is possible practically. If anybody has any better advice, I am open for any suggestions.
Thank you in advance
I'm not sure that a unique custom post type per user is the best way to implement what you're wanting to achieve. If you have 100 users, you will have 100 custom post types making the wp-admin a nightmare as the left menu would grow with so many menu-items.
Wouldn't it be easier to just use a normal post type and then have the page that shows the user's dashboard filter the posts to only show posts where the user is the post_author? You could then add a hook to catch when a user registers and create the example post, you could modify the code below and add it to your functions.php:
add_action( 'user_register', 'myplugin_registration_save', 10, 1 );
function myplugin_registration_save( $user_id ) {
$userPostsCategory = 3;
// Create post object
$my_post = array(
'post_title' => 'Sample Story' ),
'post_content' => 'You can edit this or create a new story',
'post_status' => 'publish',
'post_author' => user_id,
'post_category' => array( $userPostsCategory )
);
// Insert the post into the database
wp_insert_post( $my_post );
}
This method will lower the number of customisations you'd have to do to your themes and make management of the posts a little easier.
Further reading on this:
User registration hook
Inserting a post using wp_insert_post
I have the next WP_Query in footer.php in my wordpress:
wp_reset_postdata();
$argsLast = array(
'post_type' => 'post',
'posts_per_page' => 3,
'orderby' => 'date',
'order' => 'DESC',
'category__not_in' => array(193,189,192,195,207,190,213),
);
$ultimosposts = new WP_Query( $argsLast );
And it works fine in all pages of my wordpress except the category pages.
I have done several tests and the paremeter which doesn't work are 'order' or 'orderby'.
I would be grateful if someone could explain what is going on.
SOLVED: The problem was caused by a plugin: Sort Categories By Title
I deactivated the plugin and I'm sorting the posts in category using the next code in functions.php of my theme (a lot of thanks to #PieterGoosen, now I understand much better the queries in Wordpress):
add_action( 'pre_get_posts', 'orden_posts_categoria');
function orden_posts_categoria($q){
if (!is_admin()
&& $q->is_main_query()
&& $q->is_category()
) {
$q->set( 'orderby', 'title' );
$q->set( 'order', 'ASC' );
}
}
Note: this code is from #PieterGoosen
In this way, I modify the main query of wordpress. So it is very important setting the correct conditions in the selective structure.
Glad you have deactivated the plugin as in my opinion, the plugin is a pile off crap due to the fact that it breaks page functionalities. I can only speculate, but it either uses pre_get_posts wrongly or it uses query_posts which you should never ever use.
To solve your issue, you need to go back to the dafault loop which should look like this
if ( have_posts() ) { // Sometimes category pages don't have this, not really necessary
while ( have_posts() ) {
the_post();
// Your markup and template tags
}
}
You again should see posts on your category page ordered by date as per default.
Now, to solve the issue of sorting your posts by title on category pages, we will use pre_get_posts to alter the main query variables before the main query run. This is the recommended method, you should never replace the main query with a custom one to solve these kind of issues. It leads to other issues, specially wrong posts and wrong pagination
In your functions.php or your own custom plugin, add the following
add_action( 'pre_get_posts', function ($q )
{
if ( !is_admin() // Check that we are on the front end and not back end
&& $q->is_main_query() // Make sure we only alter the main query
&& $q->is_category() // Only target category pages
) {
$q->set( 'orderby', 'title' );
$q->set( 'order', 'ASC' );
}
});
The check I have done is very very important. pre_get_posts alters all instances of WP_Query, not only the main query, and this happens back end and front end and on all pages. Always make sure that you use these checks when using pre_get_posts
You should now have your category pages sorted by post title, and your custom query 8n the footer should also now correctly on category pages.
Just one last tip, to avoid custom filters altering your custom WP_Query instances, use 'suppress_filters' => true in your query arguments. get_posts does the same to avoid custom filters altering the output
EDIT
Just on the issue of queries, you should take your time and read this post I have done on the subject of the main query and custom queries
I'm looking for some help, for some reason this code isn't working when trying to display total image attachments on the main index.php page.
// Get all the attachments
$attachments = get_posts ( array(
'numberposts' => -1,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
) );
// Count all the attachments
$total = count( $attachments );
The problem is, the loop is in the main index.php page, but it's calling a post.php template so I have placed this code there instead (I'm assuming that's still in the loop?) I am then calling $total just below it where I want to show "View all # images".
Any ideas why this is just displaying the number as 0 even though I have added an image gallery to the post using the basic Wordpress gallery media library?
Thanks
The attachment count only increases if it's attached to a post. You can force the count by adding this:
$wp_taxonomies['category']->update_count_callback = '_update_generic_term_count';
in a function in your functions.php something like this:
function change_category_arg() {
global $wp_taxonomies;
if ( ! taxonomy_exists('category') )
return false;
$wp_taxonomies['category']->update_count_callback = '_update_generic_term_count';
}
add_action( 'init', 'change_category_arg' );
Explanation:
This is significant in the case of attachments. Because an attachment
is a type of post, the default _update_post_term_count() will be used.
However, this may be undesirable, because this will only count
attachments that are actually attached to another post (like when you
insert an image into a post). This means that attachments that you
simply upload to WordPress using the Media Library, but do not
actually attach to another post will not be counted. If your intention
behind associating a taxonomy with attachments was to leverage the
Media Library as a sort of Document Management solution, you are
probably more interested in the counts of unattached Media items, than
in those attached to posts. In this case, you should force the use of
_update_generic_term_count() by setting '_update_generic_term_count' as the value for update_count_callback.
from Wordpress Codex on register_taxonomy
I have changed the default permalink of my website to Custom permalink (/%post-name%)
Now all posts require slug values .
which is not present currently.A slug is automatically added when a post is published or updated if slug screen option is unable ,but in my case now i have unable the slug option for all post earlier this was disabled and Now I want to update each post nothing want to add or delete just want to update all posts .
Currently number of posts in database is 200000,
Please suggest any efficient query or any method so that my task can be accomplished.
Thanks,
Monika
Try this plugin, it should do the job:
http://www.jerrytravis.com/598/wordpress-plugin-to-generate-post-slugs
Also this chunk of code can do the job, but you have to add some limits to avoid the script to crash due to the max limit of execution:
// get all posts
$posts = get_posts( array ( 'numberposts' => -1 ) );
foreach ( $posts as $post )
{
// check the slug and run an update if necessary
$new_slug = sanitize_title( $post->post_title );
wp_update_post(
array (
'ID' => $post->ID,
'post_name' => $new_slug
)
);
}
Credit for the code:
https://wordpress.stackexchange.com/questions/46086/regenerate-slugs-from-title-of-posts