Currently I am trying to fetch data from an external page, which I have stored via a custom field and store it into the top portion of my WordPress the_content when the post is saved.
The steps are accordingly.
Save URL into custom field.
Save Post
Behind the scenes while the post is publishing to database, grab the contents from the url, and set them into the_content on WordPress, without removing the existing the_content data.
Whats the best way to do this?
Currently I am trying to fetch data from an external page, which I have stored via a custom field and store it into the top portion of my WordPress the_content when the post is saved.
The steps are accordingly.
Save URL into custom field.
Save Post
Behind the scenes while the post is publishing to database, grab the contents from the url, and set them into the_content on WordPress, without removing the existing the_content data.
Whats the best way to do this?
What kind of data? HTML? JSON? You did not provide enough specifics for us to actually help you with this .. including what kind of Post Type.
There are numerous filters you can use for this, this is a ROUGH markup of PHP to do something like this before the data is inserted (based on limited information provided)
add_filter( 'wp_insert_post_data', 'insert_custom_data_before_content', 10, 2 );
function insert_custom_data_before_content( $data, $postarr ){
$external_url = sanitize_text_field( $_POST['external_url'] );
$request = wp_remote_get( $external_url );
if( ! is_wp_error( $request ) && wp_remote_retrieve_response_code( $response) === 200 ){
if( $response = wp_remote_retrieve_body( $request ) ){
$data['post_content'] = wp_kses( $response, true ) . $data['post_content'];
}
}
return $data;
}
This is assuming you have already added your own custom field with a name
attribute of external_url
(which you should add your own PHP to check that value)
There's also save_post
when a post is saved (after being updated) which also passes an argument if it was an update or not.
You also need to keep in mind handling data sanitation, ESPECIALLY if you're pulling data from an external URL to insert into your database .. that opens up all kinds of potential security concerns.
https://codex.wordpress/Validating_Sanitizing_and_Escaping_User_Data