Wordpress: Access URL for post which was just created - php

I am using WordPress to create a website which allows users to upload files of hiking paths (gpx (xml) files).
To do this the user access a page called "Create new track" (this is a WordPress page with a specific template). Via a php created form, the user enters the name of the hike, a short description and chooses the file to upload. My code then makes the usual checks on the entered data and chosen file. If all checks are passed, the file is uploaded to the server and a new post is created (adding the entered title and description and file attached to the post).
I want that once the file has been uploaded and the new post has been created then the user accesses a webpage where he can view the newly created hike. I would like this page to be a second WordPress page called "Edit track" which uses a second specific template.
My current plan is that would use $track_ID (see code - this is the ID of the newly created post) and add this to the url of the "Edit track" url in the form of a url parameter. When the "Edit track page is automatically opened after successful creation of the track then the url param is read and the appropriate track can be edited.
My problem is, what code do I need to write such that once the new post is successfully created the "Edit track" page is accessed??
I am completely stumped! I have tried using php and Javascript, but cannot workout how to do this. All ideas welcome!
The frame of my code is attached.
add_shortcode('sut_form', 'sut_form_shortcode');
function sut_form_shortcode() {
if (isset( $_POST['sut_form_create_track_submitted'] ) &&
wp_verify_nonce($_POST['sut_form_create_track_submitted'], 'sut_form_create_track') ) {
// LOTS OF CHECKS ON WHAT HAS BEEN ENTERED
}
else // ALL CHECKS PASSED, SO WE CAN CREATE THE POST
{
$track_data = array(
'post_title' => $sut_track_name,
'post_content' => $sut_track_text,
'post_status' => 'pending',
'post_author' => $current_user->ID,
'post_type' => 'tracks'
);
// Create track post and attach image
if ($track_id = wp_insert_post($track_data)) { // POST CREATED
wp_set_object_terms( $track_id, (int)$_POST['sut_track_category'], 'track_category'); // CATEGORY ASSIGNED TO POST
update_field('field_5bf39d97d1e8d', $movefile['url'], $track_id); // UPLOADED FILE ATTACHED TO POST
// PROBLEM!!! HOW DO I KNOW ACCESS THE URL FOR POST WHICH HAS JUST BEEN CREATED?
}
}
}

Your function is registered with add_shortcode, so it is executed during page content rendering, it is too late to use header("location... since headers could be already sent to client.
The only solution I can think of, without changing your code and without knowing your entire project is to print a JavaScript snippet, something like this:
$permalink = get_permalink($track_id);
echo("<script>window.location.replace('$permalink');</script>");
It is not too neat but should work.

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

How to make woocommerce shop page with a custom post type +and a checkout page

I am sharing 3 screens step by step will be through woocommerce.
I have a shop page. On selecting a product, I will go to a front end form for creating a post. After creating a post I will go to checkout page.
My question is that, can I get the middle one (front end form for creating a post) in woocommerce platform ?
Please look my shared screen for understanding it better.
Thank you
First Screen
Second Screen
Third Screen
My question is that, can I get the middle one (front end form for
creating a post) in woocommerce platform ?
Sure, but you have to save the data from step 2 in the current session (cart).
Only when an order is created, collect the session data and create the (custom_post_type) job post. You don't want to create the job post before the order is completed / paid for.
Your question is very general, so you can expect a similar answer. We do not build complete plugins here. You will need to use multiple hooks to complete this.
EDIT: some more info
# step 2, collect, sanitize and validate the form values.
I would save this data in the cart session. something like this:
// I don't know how and where you collect the step 2 data,
// so i can't provide a hook for this function.
function step_2_data_to_session() {
global $woocommerce;
$step_two_data = array();
// validate and sanitize data first
// save data to woocommerce session
$woocommerce->session->set('step_two_data', $step_two_data );
}
Then when the user pays and creates an order, use a hook to collect the session data and save it to your costom post type.
add_action('woocommerce_checkout_update_order_meta', 'new_order', 10, 2)
function new_order($order_id, $data) {
global $woocommerce;
// At this point the order is created and the session data is still alive.
if(! is_admin() ) {
$step_two_data = $woocommerce->session->get('step_two_data');
if($step_two_data) {
$args = array(
'post_author' => get_current_user_id(),
'post_title' => 'The Job title here',
'post_type' => 'job',
'post_status' => 'publish'
);
$new_job_post_id = wp_insert_post($args);
if($new_job_post_id) {
// Job post is saved now..
// Now you'll probably want to add step_two_data as meta data to the post.
}
}
}
}
NOTE: I haven't tested this code, error handling is not included, etc. This is just a pointer how to save the session data when the order is created.
You'll have to do much more, for example, i see that the job listing has a set expiration date. I would use a cron-job to daily check which jobs have to be removed, with the same cron i would also inform customers their job post 'will be removed in 2 days' etc etc ;-)
Regards, Bjorn

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

How to to implement a forgot password feature using the Google Identity Toolkit in php

I am trying to add google identity toolkit in php. Signin option is working correctly but when i am clicking on problem in sign in link it is showing capthca after submitting captcha it is not navigating to any url.
email.php
<?php
include "identity-toolkit-php-client-master/src/GitkitClient.php";
$gitkitClient=new Gitkit_Client();
$oob_response = $gitkitClient->getOobResults($_POST);
$oob_link = $oob_response['oobLink'];
echo json_encode($oob_response);
?>
email.php is the oobactionurl file. when i am using this code I am getting this error .image
You need to create a php file to retrieve and send the reset link to the user. Make sure the oobActionUrl widget option points to this file. Within the file, you'll get the generated link and additional information by calling $gitkitClient->getOobResults($_POST). It should also work if you exclude $_POST, as the function will check the post contents if no arguments are passed. Then, you can get the link itself like this:
$oob_response = $gitkitClient->getOobResults($_POST);
$oob_link = $oob_response['oobLink'];
From there, you can use your email function of choice to send it to the user. The returned array should contain the following.
'email' => email of the user,
'oldEmail' => old email (for ChangeEmail only),
'newEmail' => new email (for ChangeEmail only),
'oobLink' => url for user click to finish the operation,
'action' => 'RESET_PASSWORD', or 'CHANGE_EMAIL',
'response_body' => http response to be sent back to Gitkit widget
Let me know if you have any further questions.

Wordpress 'add_post_meta' - Data doesn't display on page until post is manually opened and 'updated'

I'm using PHP automation to create new Wordpress posts (with wp_insert_post). I'm also using 'Simple Fields' to add additional meta fields for displaying on the front end.
My code creates the Wordpress post, keeps the post ID in a variable and then goes on to add the required meta data immediately afterwards.
Trimming all the other clutter, this is my process:
// Insert the post into the database and return the post ID
$post_id = wp_insert_post( $my_post );
// Add '$price' to relevant meta field
update_post_meta($post_id, '_simple_fields_fieldGroupID_1_fieldID_4_numInSet_0', $price);
This works fine, when I check the database, the 'price' meta field has the correct information inserted.
The problems starts when I try to extract it using:
echo simple_fields_value("price", $post->ID);
The code works - But the only way I can get it to pull the data is to log into the Wordpress admin, open the post for editing and then hit 'Update'.
Providing I open every post and hit 'Update', there's not a problem with my code... it does everything as expected.
My question is, what is the 'Update' button doing that I'm not? I've tried using 'wp_update_post' to re-open the post and save after the meta data is added to see if that helped, but it doesn't.
// Open and update post to ensure meta data saves correctly
$update_post = array(
'ID' => $post_id,
'post_title' => $title
);
// Update the post into the database
wp_update_post($update_post);
Your help on this would be much appreciated,
It looks like you are using the Simple Fields Plugin. I have never personally used this plugin, however I had a quick look and it looks like the plugin runs a few extra things on the save of the post. Here is one of the queries it uses for some sort of cacheing :
// Save info about the fact that this post have been saved. This info is used to determine if a post should get default values or not.
update_post_meta($post_id, "_simple_fields_been_saved", "1");
Since you are inserting this meta value manually, I would recommend you use the native wordpress get_post_meta function to call the value, your query should look something like this:
get_post_meta($post->ID, "_simple_fields_fieldGroupID_1_fieldID_4_numInSet_0");

Categories