I'm working on a WordPress plugin which allows me to choose the proper upload folder regarding the custom post type, taxonomies terms and the title.
I can grab each kind of data when the post is saved, no problem. But how to grab for example a title of a post which hasn't been published?
I tried $_POST, by adding first a name in the title textarea field of WordPress (because it hasn't one) but this totally broke my upload filter with an internal error 500.
I have a partially working code. In a PHP file, I'm enqueuing this Ajax script:
function get_unposted_post_title( $hook ) {
if ( ($hook == 'post-new.php') || ($hook == "post.php" && $_GET['action'] == "edit") ) {
echo "<script>
function posturl(title, url) {
$.ajax({
type: 'POST',
url: url,
data: title,
success: function(title, url) {
console.log(title);
}
});
}
setInterval( function() {
var title = $('#post-title-0').val();
var url = '" .GIA_PLUGIN_URL. "test.php';
posturl(title, url);
}, 5000);
</script>";
}
}
add_action( 'admin_enqueue_scripts', 'get_unposted_post_title', 10, 1 );
Then, in the root of my plugin, I have created a test.php file:
<?php
$keys = array_keys($_POST);
if(isset($keys) && !empty($keys[0])) {
print_r( $keys[0] );
}
?>
This function displays the updated title in the console.log as expected.
However, I'm unable to grab $keys[0]
without making the upload filter crashed. Uploaded files are properly moved with the updated path of my filter, except for the last folder which must have a sanitized version of the post title. I'm hooking into wp_handle_upload_prefilter
and wp_handle_upload
.
If you look at the provided code, I should be able to grab keys[0]... but the problem is that keys[0] give me 'name'... keys[1] give me 'action', keys[2] give me 'wp_nonce'. I don't know why I can't grab keys[0] correctly, it seems that $keys of my test.php isn't updated with a proper value for the key 0.