WordPress snippet: the action save_post

When adding additional fields to pages and posts, or to their own Custom Post Type ( CTP ), you must record an action to store this new data. The implementation of this procedure is basically always the same, changing only the fields and how to save, the extra data can reside in a 'custom field', or the post meta table, or on one or more tables personal. A skeleton useful is the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/ * Join the hook * /
, 'did_post_update' , 10 , 2 ) ; add_action ('save_post', 'did_post_update', 10, 2);

$ID , $post ) { did_post_update function ($ id, $ post) {

/ / Local Variables
/ / Exclude negative values ​​(and possibly characters)
absint ( $ID ) ; $ ID = absint ($ id);
/ / Post type (CPT)
get_post_type ( ) ; $ Post_type = get_post_type ();
get_post_type_object ( $post_type ) ; Post_type_object get_post_type_object $ = ($ post_type);
'' ; $ Capability ='';

/ / Exit if autosave
defined ( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE === true ) { if ( defined ('DOING_AUTOSAVE') && DOING_AUTOSAVE === true) {
return;
}

/ / Exit if the post is not of our type
! in_array ( $post_type , array ( 'post_type_id' ) ) ) { if ( in_array ($ post_type, array ('post_type_id'))) {
return;
}

/ / Further control via the nonce WordPress
isset ( $_POST [ 'nonce_id' ] ) && ! wp_verify_nonce ( $_POST [ 'nonce_id' ] , 'uniqid' ) ) { if ( isset ($ _POST ['nonce_id']) &&! wp_verify_nonce ($ _POST ['nonce_id'], 'uniqid')) {
return;
}

/ / We find the correct capability in relation to our post type
isset ( $post_type_object -> cap -> edit_posts ) ) { if ( isset ($ post_type_object -> cap -> edit_posts)) {
$post_type_object -> cap -> edit_posts ; $ Capability = $ post_type_object -> cap -> edit_posts;
}

/ / Bye bye if we do not have the permissions
! current_user_can ( $capability ) ) { if (current_user_can ($ capability)) {
return;
}

/ **
* If we come here we can save our data
* /

There are no comments for this post

Leave a comment

TAG XHTML PERMITS: CODE ENTRY:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL