What hook to use after updating post? - php

So I have a custom field X that saves it's value naturally upon submitting or updating post. User enters the value of this field.
What I want to do, is after the post is updated, I want to update another custom post meta field called Y automatically with the value of X. So the Y field should be updated without the user knowing it (in the back end), what is the correct hook and function that I need to use?

Hello Here you can use save_post hook which is call wether the post is created or updated.
function my_custom_field_save( $post_id ) {
// do your stuff here....
}
add_action('save_post', 'my_custom_field_save');
More About save_post hook
i hope this will help you.

you can used the save_post action hook to update meta after the triggered whenever a post or page is created or updated
add_action( 'save_post', 'update_custom_value', 10, 3 );
function update_custom_value( $post_id,$post, $update ) {
if ( 'post'== $post->post_type ) {
if ( isset( $_REQUEST['x'] ) ) {
$x= $_REQUEST['x'];
update_post_meta($post_id,'Y', $x);
}
}
}
//Edit For update Y only one time when post is create
add_action( 'save_post', 'update_custom_value', 10, 3 );
function update_custom_value( $post_id,$post, $update ) {
if ( 'post'== $post->post_type ) {
if ( isset( $_REQUEST['x'] ) ) {
$x= $_REQUEST['x'];
if(get_post_meta($post_id,'Y',true)=='')
{
update_post_meta($post_id,'Y', $x);
}
}
}
}

Related

Get page ID in user_register hook Wordpress

in my site I have 2 differents forms for registration. The difference between them that is when I use the second I update a meta info for a user that normally is blank.
I've added the Facebook SSO and works fine only for the first form.
When I use it for the second it doesn't recognize the origin and register the user as the first one (without update meta info).
I've tried to use the register_user hook
function myplugin_registration_save( $user_id ) {
global $post;
if ($post->ID == 816) {
update_user_meta($user_id, 'user_type', 'couple');
}
}
add_action( 'user_register', 'myplugin_registration_save', 999 );
but this hook doesn't return the post ID.
How can I detect I'm in the second form and launch the update_user_meta function when the post id is 816?
Thanks
function myplugin_registration_save( $user_id ) {
$currentPageId = get_the_ID();
if ($currentPageId == 816) {
update_user_meta($user_id, 'user_type', 'couple');
}
}
add_action( 'user_register', 'myplugin_registration_save', 999 );
Try this one it will surely give you the current page id..

how to create unique reference number - wordpress

I have Suppliers which have their own products. WP backend is almost redesigned and there I have a page(with form) where 'admin' can add new supplier and I need to create unique a reference number for each supplier when form will be submitted.
Plus, I have a "Sort by" dropdown and one of the sorting options is by "Reference number".
At first, I thought to use the POST ID as reference number, but don't think that this can be best solution, as POST IDs will be different when some posts will be removed. Also I was thinking to use uniqid() function with some digit limit and only digits.
What is best to reach this? Any ideas?
You can specify a new custom meta field for (i.e. supplier_id) and create a function which ensure that this supplier_id is unique. This function will be executed every time when a supplier form submitted.
The action hook save_post is triggered whenever a post or page is created or updated. So we can use it for this purpose.
From the documentation:
save_post is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. The data for the post is stored in $_POST, $_GET or the global $post_data, depending on how the post was edited. For example, quick edits use $_POST.
Since this action is triggered right after the post has been saved, you can easily access this post object by using get_post($post_id)
Example:
function save_supplier_id( $post_id, $post, $update ) {
$post_type = get_post_type($post_id);
if ( "supplier" != $post_type ) return;
if ( isset( $_POST['supplier_id'] ) ) {
$my_supplier_id = $_POST['supplier_id'];
if ( ! is_int( $my_supplier_id ) ) $my_supplier_id = 1;
$all_other_suppliers = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'supplier',
'post__not_in' => array( $post_id )
));
$all_other_ids = array_map( function( $supplier ) { return $supplier->ID; }, all_other_suppliers );
if ( count( $all_other_ids ) && in_array( $my_supplier_id, $all_other_ids ) ) {
// ID is already in use by another supplier, let's create an new one
$my_supplier_id = max( $all_other_ids ) + 1;
}
update_post_meta( $post_id, 'supplier_id', $my_supplier_id ) );
}
}
add_action( 'save_post', 'save_supplier_id', 10, 3 );
Explantion:
The format for supplier_idis simple a consecutive number. If the provided id is not an integer, we set it to 1. Now we get all other supplier id's and check if the give id no occur twice. If so, the we get the max id and increase it by 1.

Wordpress Update Post Hook in Admin View

i need a hook for the moment when an admin updates a post. (Click on update button). After the post is successfully updated.
The reason is, i have to call a function to update something for another plugin.
Everything i tried so far, is not working.
add_action( 'save_post', 'wpse41912_save_post' );
add_action( 'edit_post', 'wpse41912_edit_post' );
add_action( 'transition_post_status', 'wpse41912_transition_post_status' );
add_filter( "edit_post_{$field}", 'filter_edit_post_field', 10, 2 );
add_action( 'admin_head-post.php', 'admin_head_post_editing' );
add_action( 'admin_head-post-new.php', 'admin_head_post_new' );
add_action( 'admin_head-edit.php', 'admin_head_post_listing' );
In Everything function i wrote this, and i didnt see the echo or the alert box.
echo "my_update_user_meta";
$text = "my_update_user_meta";
echo '<script type="text/javascript">alert("' . $text . '")</script>';
Edit: i was missing the 3,4th parameter.
My Code now
add_action( 'save_post', 'mmx_save_post_action', 10, 3 );
function mmx_save_post_action( $post_id, $post, $update ) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) { // keine Aktion bei Autosave
//autosave
}else{
//no autosave
if ( is_admin() && current_user_can( 'manage_options' ) ) {
//admin panel && permission ok
//call function
}
}
}
When a post is updated there are some hooks that are fired:
'pre_post_update' is an action fired just before the post is updated, the argument passed are 2: $post_ID and $data that is an array of all the other database colums of the post table
'transition_post_status' is an hook fired on update, and pass 3 arguments: $new_post_status, $old_post_status and $post (object).
Then, there are other 2 transition hooks fired, but they are dynamic named, it means that the effective action fired depends on the old and the new post status.
"{$old_status}_to_{$new_status}" and "{$new_status}_{$post->post_type}". First pass the only the post object as argument, the second pass the post id and the post object. Find documentation here.
'edit_post' that pass 2 arguments: $post_ID and $post (object)
'post_updated' that pass 3 arguments: $post_ID, $post_after (post object after the update), $post_before (post object before the update)
Another dynamic hook: "save_post_{$post->post_type}" that depends on post type, e.g. for standard posts is 'save_post_post' and for pages is 'save_post_page', this hook pass 3 arguments: $post_ID, $post (object) and $update that is a boolean (true or false) that is true when you perform an update, in fact this hook is fired also when a post is saved for first time.
'save_post' that is fired both on update and on first saving, and pass the same 3 arguments of the previous hook.
'save_post_{$post_type}' that is fired both on update and on first saving, and pass the same first 2 arguments of the previous hook.
Finally you have 'wp_insert_post', that is fired both on update and on first saving, and pass the same 3 arguments of the previous 2 hooks.
These hook are fired every time a post is updated, both via admin pages in backend and via when updated "manually" using wp_update_post or wp_insert_post functions.
When the post is updated using admin pages there are additional hooks fired, an example is 'update_post_redirect' or 'post_updated_messages'. (See this and this WPSE answers for usage examples).
Note that if you want make use of some hooks argument, that isn't the first, one you have to explicitly declare it in add_action call.
E.g. if you want to use the '$update' argument (that is the 3rd) of the 'save_post' hook you need to add 3 as $accepted_args param on add_action (see docs):
// if you don't add 3 as as 4th argument, this will not work as expected
add_action( 'save_post', 'my_save_post_function', 10, 3 );
function my_save_post_function( $post_ID, $post, $update ) {
$msg = 'Is this un update? ';
$msg .= $update ? 'Yes.' : 'No.';
wp_die( $msg );
}
Last note regard timing: you must be sure that add_action is called before the action is triggered, or it will do nothing.
E.g. this code:
wp_update_post( $post );
add_action( 'save_post', 'my_function', 10, 3 );
will do nothing, because the action is added after the hook is fired. Here is simple to recognize it, in real world code isn't always so.

Add custom buttons with custom actions in Edit Post screen in WordPress?

I am creating something for a client and I have a Class that I created with a Custom Post Type called 'PuSH Feeds' and when the user adds a new post and publishes it they can then click on one of two buttons that I have in the Custom Meta Box.
One button is for 'Subscribe' and the other for 'Unsubscribe'. I am using the save_post action hook and testing if the $_POST global has that 'pushfeed-subscribe' or 'pushfeed-unsubscribe' and then do what I need to do. However for some reason I have found that once I click on the subscribe on my local machine stops the script because it says it did 100 consecutive calls etc and I end up with loads of duplicate posts with no title.
What would be the best way to avoid this and is there a better hook I can use for these special custom actions I want to activate of subscribing to a feed (which goes into another class and performs the subscribe method)?
This is the markup I have for those two buttons I mentioned with is inside the Metabox
<input type="submit" class="button-secondary" name="pushfeed-subscribe" id="pushfeed-subscribe" value="Subscribe">
<input type="submit" class="button-secondary" name="pushfeed-unsubscribe" id="pushfeed-unsubscribe" value="Unsubscribe">
Then I have this for the action hook:
add_action( 'save_post', array( $this, 'pushfeed_save_post_meta' ) );
The actual hook is like this:
public function pushfeed_save_post_meta( $post_id ) {
// Bail if we're doing an auto save
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['pushfeed-nonce-field'] ) || !wp_verify_nonce( $_POST['pushfeed-nonce-field'], basename( __FILE__ ) ) ) return;
// If Subsctiption ID is empty, generate a random long number and save it
if ( empty( $_POST['pushfeed-subscription-id'] ) ) {
$random_number = substr(number_format(time() * mt_rand(),0,'',''),0,10);
$pushfeed_subscription_id = $random_number . $post_id;
update_post_meta( $post_id, 'pushfeed-subscription-id', $pushfeed_subscription_id );
}
...
if ( isset( $_POST['pushfeed-subscribe'] ) || isset( $_POST['pushfeed-unsubscribe'] ) ) {
$subscription_domain = get_post_meta($post_id, 'pushfeed-domain', true);
$subscription_id = get_post_meta($post_id, 'pushfeed-subscription-id', true);
$subscription_feed_url = get_post_meta($post_id, 'pushfeed-feed-url', true);
$subscription_callback_url = $subscription_domain . '/pushfeed/' . $subscription_id;
$sub = PuSHSubscriber::instance($subscription_domain, $subscription_id, 'PuSHSubscription', new PuSHEnvironment());
if ( isset( $_POST['pushfeed-subscribe'] ) ) {
$sub->subscribe($subscription_feed_url, $subscription_callback_url);
} elseif ( isset( $_POST['pushfeed-unsubscribe'] ) ) {
$sub->unsubscribe($subscription_feed_url, $subscription_callback_url);
}
}
}
I am trying to find out why is it that the post is saving multiple duplicates with no title.
But above all I would like to know if there is a better action hook I can call for these two custom actions.
Update :
Hi everyone. I ended up using an Ajax request using the wordpress admin-ajax.php when clicking a button and then firing of the subscription method. Once that is done the subscription method will do a get request and if returns a 200 code then the method returns true to the Ajax.
The problem is probably caused by your use of a submit button.
Custom Meta Boxes are not intended to include submit buttons. The idea is that they contain form fields that get submitted when you click on the standard "Update" button. You can then save what is submitted in the save_post action hook.
Using a submit other than "Update" may be confusing WordPress and causing your problem.
I suggest that you change your Custom Meta Box to have a checkbox for Subscribe or a radio button for Subscribe/Unsubscribe that you can look at in the action hook.

How to add custom bulk actions in WordPress list tables?

I am developing a plugin for that I have to black list users, so I need to be display one more dropdown item called Black List inside the Bulk Actions dropdown in the Users page, after the Delete option. But I'm unable to see from where these two actions are coming from and also how to black list a particular user.
My idea is to add one more field is_blacklisted in user table as Boolean with default value false and when apply Black List action it changes to true. Any other thoughts?
There's a filter, but it's only useful to remove bulk actions.
From this WPSE question, answer and comments, there's the following workaround: add a custom option to the dropdown with jQuery and hook into admin_action_$your-action to catch the submission.
The hook admin_footer-$current_page is used to print our JavaScript on a specific admin page (adjust to use in other screens).
add_action( 'admin_footer-users.php', 'bulk_footer_so_23541269' );
add_action( 'admin_action_black_list', 'bulk_request_so_23541269' );
function bulk_footer_so_23541269()
{
# global $typenow; if( $typenow != 'page' ) return; // if used on edit.php screen
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('<option>').val('black_list').text('Black list')
.appendTo("select[name='action'], select[name='action2']");
});
</script>
<?php
}
function bulk_request_so_23541269()
{
# Array with the selected User IDs
wp_die( '<pre>' . print_r( $_REQUEST['users'], true ) . '</pre>' );
// $_REQUEST['post'] if used on edit.php screen
}
Your doubt about blocking a user deserves another question, but I'd start a research here first.
Proper support with add_filter( 'bulk_actions-screenid', 'register_my_bulk_actions' ) is arriving in Wordpress 4.7 .
Quoting the announcement post:
To add an option in the Bulk Actions dropdown HTML element, register a callback on the bulk_actions-{screen_id} filter that adds the new option onto the array. Replace {screen_id} with the ID of the admin screen to offer the bulk action on.
To add a bulk action “Email to Eric,” we could use the following code:
add_filter( 'bulk_actions-edit-post', 'register_my_bulk_actions' );
function register_my_bulk_actions($bulk_actions)
{
$bulk_actions['email_to_eric'] = __( 'Email to Eric', 'email_to_eric');
return $bulk_actions;
}
To handle a bulk action form submission, register a callback on the handle_bulk_actions-{screen_id} filter for the corresponding screen. The filter expects the redirect URL to be modified, so be sure to modify the passed $redirect_url. This allows us to carry success or failure state into the next request to display a notice to the user. The other callback arguments will differ depending on the screen here to include contextually relevant data.
To add a bulk action handler for emailing the selected posts, we could use the following code:
add_filter( 'handle_bulk_actions-edit-post', 'my_bulk_action_handler', 10, 3 );
function my_bulk_action_handler( $redirect_to, $doaction, $post_ids )
{
if ( $doaction !== 'email_to_eric' ) {
return $redirect_to;
}
foreach ( $post_ids as $post_id ) {
// Perform action for each post.
}
$redirect_to = add_query_arg( 'bulk_emailed_posts', count( $post_ids ), $redirect_to );
return $redirect_to;
}
Showing notices: We could use the existing notice hooks to let the user know what happened, depending on the state we set in the URL:
add_action( 'admin_notices', 'my_bulk_action_admin_notice' );
function my_bulk_action_admin_notice()
{
if ( ! empty( $_REQUEST['bulk_emailed_posts'] ) ) {
$emailed_count = intval( $_REQUEST['bulk_emailed_posts'] );
printf( '<div id="message" class="updated fade">' .
_n( 'Emailed %s post to Eric.',
'Emailed %s posts to Eric.',
$emailed_count,
'email_to_eric'
) . '</div>', $emailed_count );
}
}

Categories