How do I generate numeric titled wordpress posts? - php

I would like to automatically generate some sequential Wordpress posts that have numeric titles, for example "1", "2", "3"... etc.
I'm looking for an automatic system since I would like my posts to go from "1" to "999999".
No post content or meta is required, only the titles.
I'm aware of wp post generate but I have no idea on how to use it so that the post titles have the requirements explained above.
I'm working on a demo project so search engine optimization is not a concern at the moment.
CLI usage is accepted.

You can achieve that quite simply by using a for loop with any arbitrary range (1-99 for example - or any other range you prefer)
for i in {1..99}; do wp post create --post_title="This is post number $i" --post_status=publish; done
This will call the wp post create command on each iteration of the loop and append the number to the post title.

<?php
// Create post object usinf for loop
for($i=1;$i<=9999;$i++){
$my_post = array();
$my_post['post_title'] = '<?php echo $i;?>';
$my_post['post_content'] = 'This is my post-<?php echo $i;?>';
$my_post['post_status'] = 'publish';
$my_post['post_author'] = 1;
$my_post['post_category'] = array(0);
// Insert the post into the database
wp_insert_post( $my_post );"
}
?>

wordpress appends a numeric value automatically if there's an existing post with the same post-title.
so if the permalinks are set to be postname the URL will look as follow:
my-post
my-post-1
my-post-2
etc

Related

Featured image via built-in Wordpress function instead of ACF (Pro) image field

I have a news website with over 3000 posts. The previous website builder did not use the built-in functionality of Wordpress for the featured image, but used an ACF (Pro) image field instead.
On the new website I would like to use the standard function of Wordpress. I just have no idea how to set the images from the ACF (Pro) image field as a featured image via the built-in Wordpress function.
Is there a script that can do that automatically?
I don't like having to do more than 3000 messages manually.
So the image should be from this:
To this:
I've searched all over the internet for a solution to this, but couldn't find anything.
Thank you very much in advance for any help.
We can make a simple script to fix your post thumbnails.
For easiest implementation lets just add this function to your functions.php which will run when we your site loads.
You want to run this on over 3000 news posts. This means your site will take a few moments, maybe minutes, to run the script before your site eventually loads.
If you are using this on a live environment, lets add a URL parameter to only allow this to run when param is true, for example...
https://www.example.com/?fix_post_thumbs=true
Here is the code you need to add to your functions functions.php...
Please read comments in code so you know what is happening.
// fix post thumbs
function fix_post_thumbs() {
// if current user is admin and url param fix post thumbs is set
if(current_user_can('administrator') && isset($_REQUEST['fix_post_thumbs'])) {
// if url param for fix post thumbs is true
if($_REQUEST['fix_post_thumbs'] === 'true') {
// our wp query args for which we want to run this script
// change post type value to your news post type
$args = array (
'post_type' => 'post',
'post_status' => 'any',
'posts_per_page' => -1
);
// count the process posts
$count = 0;
// set our wp query
$query = new WP_Query($args);
// if we have posts to loop
if($query->have_posts()):
// loop through our query post results
while ($query->have_posts()): $query->the_post();
// get our acf featured image field attachment id
// 3rd parma must be false just so it returns id
// you must change 'acf_featured_img' field name to your acf image field name
$attachment_id = get_field('acf_featured_img', $query->post->ID, false);
// if there is an acf featured attachment id set
if($attachment_id) {
// set the post thumbnail with acf featured image attachment id
set_post_thumbnail($query->post, $attachment_id);
// count this process
$count++;
}
endwhile;
// output message showing count of featured images set
echo '<pre>' . print_r($count . ' featured images have been set.', true) . '</pre>';
else :
// no posts found message
echo '<pre>' . print_r('Sorry, no posts matched your criteria.', true) . '</pre>';
endif;
}
}
// finally return
return false;
}
// run our fix post thumbnails
fix_post_thumbs();
This is not tested, you may want to test on some specific news post ids first via WP_Query, using post__in to only run this on selected posts. 👍🏼
Update: I've added a print_r() information showing count of how many featured images have been set once process has completed.
Plugin Update: As suggested I've created a simple plugin which you access via the Tools menu when plugin is activated.
Simply select the post type you wish to run this function on, then select the ACF image field name you want to set as the post_thumbnail, and click run.
If ACF image field for current post has no attachment value, the function will skip this post and continue processing.
See git repo plugin link below...
https://github.com/joshmoto/acf-image-set-post-thumbnail
Or download this distribution version below to install via uploading zip file to your plugins...
acf-image-set-post-thumbnail.zip

Editing serialized data WordPress dashboard

I just inherited a custom plugin that takes Formstack submissions and creates WordPress posts from them. The posts are created fine, however the form contents are stored as serialized data in post_content.
I am tasked with enabling these posts to be edited within the WP Dashboard. Currently when you click on a post title, you are presented with a page that just shows the data; no capability to edit the data.
Enabling the editor controls within "supports" in the functions.php file gives me the editor with the serialized data just dumped in the editor.
I have never had to setup a custom edit page for a specific post type in WP. Is there someone out there who can direct me so a site that explains this? I'm running in circles.
You can filter the content before it is presented in the admin editing screen.
function my_filter_function_name( $content, $post_id ) {
if(get_post_type($post_id) == 'the_post_type_in_question'){
$serialized_content = $content;
$content_array = unserialize($serialized_content);
// do something with this array to put it in the format you want
// .....
$content = $new_formatted_content;
}
return $content;
}
add_filter( 'content_edit_pre', 'my_filter_function_name', 10, 2 );
But, that doesn't seem like it's going to be of much use to you.
In your situation, I suggest you take the time to write a script to convert all those posts so that everything is stored as post meta. (create the custom fields, first).
If your theme isn't built on any framework, then I think the quickest way to create a custom field is to use the Advanced Custom Fields plugin.
Then, once you know the meta_keys, you can write that script. E.g.
$posts = get_posts('post_type'=>'the_post_type','posts_per_page'=> -1);
foreach($posts as $post){
$content_array = unserialize($post->post_content);
// how you do the next bit will depend on whether or not this is an associative array. I'm going to assume it is (because it's a little easier :) )
foreach($content_array as $meta_key=>$meta_value){
update_post_meta($post->ID, $meta_key, $meta_value);
}
// just put what you actually want as the post content back into the post content:
wp_update_post(array('ID'=>$post->ID,'post_content'=>$content_array['post_content'])); // assuming the key of the element you want to be the post content is 'post_content'
}
To run this script, you could simply create a temporary new page and then create a template file specifically for that page and put the above code into that file (then visit the page).
You need to modify the plugin so that the data is unserialized before modifying, then serialized before saving to DB...
Alternatively, try using WP's CORE functionality:
https://codex.wordpress.org/Function_Reference/maybe_serialize
https://codex.wordpress.org/Function_Reference/maybe_unserialize
https://codex.wordpress.org/Function_Reference/is_serialized
https://codex.wordpress.org/Function_Reference/is_serialized_string

Wordpress – Country Sensitive Post View

I'm looking for a solution to display posts based on the viewers
location.
For Example: I'm writing an article and set an option so it is only
visible for users from within USA.
If a user in Germany is visiting the Wordpress page, the post does
not appear.
I don't want to change content within a post, but more hide and show
them with an option for the author.
If there is some plugin, that can do this, I would highly appreciate.
Thanks.
I had similar problem. Didn't found a plugin and wrote this to query post for country of visitor: (remember to get your key at http://ipinfodb.com/)
$ip=$_SERVER['REMOTE_ADDR'];
$request = 'http://api.ipinfodb.com/v3/ip-country/?key= get your own key &ip='.$ip.'&format=json';
$response = file_get_contents($request);
$jsonobj = json_decode($response);
if ($jsonobj->countryCode == "SE"){
// args for query post for selected country $args = array ()
}
elseif ($jsonobj->countryCode == "PL"){
// args for query post for selected country $args = array ()
}
query_posts( $args );
Have a look at this discussion over here: https://wordpress.stackexchange.com/questions/26832/display-only-certain-posts-based-on-visitors-country. It might not give you a ready-to-use solution but maybe it helps as a pointer in the right direction.

How can I get an id from a simplepie post which can be used to look it up later?

I've recently started developing a portfolio website which I would like to link to my wordpress blog using simplepie. It's been quite a smooth process so far - loading names and descriptions of posts, and linking them to the full post was quite easy. However, I would like the option to render the posts in my own website as well. Getting the full content of a given post is simple, but what I would like to do is provide a list of recent posts which link to a php page on my portfolio website that takes a GET variable of some sort to identify the post, so that I can render the full content there.
That's where I've run into problems - there doesn't seem to be any way to look up a post according to a specific id or name or similar. Is there any way I can pull some unique identifier from a post object on one page, then pass the identifier to another page and look up the specific post there? If that's impossible, is there any way for me to simply pass the entire post object, or temporarily store it somewhere so it can be used by the other page?
Thank you for your time.
I stumbled across your question looking for something else about simplepie. But I do work with an identifier while using simplepie. So this seems to be the answer to your question:
My getFeedPosts-function in PHP looks like this:
public function getFeedPosts($numberPosts = null) {
$feed = new SimplePie(); // default options
$feed->set_feed_url('http://yourname.blogspot.com'); // Set the feed
$feed->enable_cache(true); /* Enable caching */
$feed->set_cache_duration(1800); /* seconds to cache the feed */
$feed->init(); // Run SimplePie.
$feed->handle_content_type();
$allFeeds = array();
$number = $numberPosts>0 ? $numberPosts : 0;
foreach ($feed->get_items(0, $number) as $item) {
$singleFeed = array(
'author'=>$item->get_author(),
'categories'=>$item->get_categories(),
'copyright'=>$item->get_copyright(),
'content'=>$item->get_content(),
'date'=>$item->get_date("d.m.Y H:i"),
'description'=>$item->get_description(),
'id'=>$item->get_id(),
'latitude'=>$item->get_latitude(),
'longitude'=>$item->get_longitude(),
'permalink'=>$item->get_permalink(),
'title'=>$item->get_title()
);
array_push($allFeeds, $singleFeed);
}
$feed = null;
return json_encode($allFeeds);
}
As you can see, I build a associative array and return it as JSON what makes it really easy using jQuery and ajax (in my case) on the client side.
The 'id' is a unique identifier of every post in my blog. So this is the key to identify the same post also in another function/on another page. You just have to iterate the posts and compare this id. As far as I can see, there is no get_item($ID)-function. There is an get_item($key)-function but it is also just taking out a specific post from the list of all posts by the array-position (which is nearly the same way I suggest).

Getting Post Information Outside the Wordpress Loop

I know there are functions to like is_single() that will return data about the page, but I'm looking for a way to get the following information outside of the loop:
The category of the single post.
AND
The title of the single post.
All I would really need is the post ID in question and I could get all the other information. I've looked through the functions reference in the codex, but I haven't found anything. Is this impossible because the script doesn't even get that information 'til the Loop runs?
(I would need this information in both the header and footer, so before and after the PHP script for the loop, if that is a problem.)
Hopefully someone can offer some insight.
EDIT: To clarify: I want the information to be from the post that is loaded in the loop on the "single" page. (AKA the post they are viewing.) So how would I get this ID in the first place? Basically, when viewing a post, I want to get its category or title, but not while the loop is going.
This is actually quite simple.
// Gets an array of post objects.
// If this is the single post page (single.php template), this should be an
// array of length 1.
$posts = get_posts();
// The post object contains most/all of the data that is accessible through the
// normal functions like `the_ID()`, `the_author()`, etc
var_dump($posts[0]->ID);
This can be performed outside of and it doesn't affect the normal loop. For example, my single.php template looks like this (line numbers included):
1. <?php
2. get_header();
3. $posts = get_posts();
4. var_dump($posts[0]->ID);
5. ?>
6. <div id="post">
You could execute your own query and return a $post object and then access it's attributes through something like
echo $post->title;
Read about $wpdb and Custom Queries on the Codex. Basically you could run a SQL query using the ID as a where filter through its $wpdb object.
Another option, more WP-like, would be to use a Custom Query Post, where you could define another loop, returning only your post using its id:
query_posts('p=2010'); // 2010 being the post's ID
Then you could run the alternative loop and use the similar $post object to display some information.
This is what I use inside the loop to run an new query; I just tried it outside the loop and it works, on a single.php template page. This will give the title of the latest post in mycategory. I don't know how to pull the category ID, though.
$my_query = new WP_Query('category_name=mycategory&showposts=1');
while($my_query->have_posts()):
$my_query->the_post();
the_title();
endwhile;
After the query has run, try running:
global $wp_query;
var_dump( $wp_query );
The information you are looking for is probably in $wp_query->query_vars or $wp_query->post
You can use the $wp_query global object, and address all returned posts like this
$wp_query->posts ; // contains an array of posts.
Then, if for instance you need to know if the first post is of a certain post_type, you can do this:
$first_post_type = $wp_query->posts[0]->post_type;
Couldn't you store the $post information in a separate variable on the page, then just echo the data you need out later when you need it (ie, outside the loop)?
This is predicated on needing the data after the initial loop has run.
The usual thing is to create "second loop" which would extract needed post, hence your needed data.

Categories