How to insert custom function into wp_insert_post

i’m trying to send push notification when the wordpress admin insert new post.

I was looking for hours where to add my function and after a lot i found core function wp_insert_post inside wp-includes/post.php

Read More

that function returns the Post_ID, so i added my custom script before return:

include '../push/send_message.php';
sendNotification($postarr['post_title'],$postarr['guid']);

The problem is that when i import these two rows here

function wp_insert_post($postarr, $wp_error = false) {
    ...
    if ( $update ) {
        do_action('edit_post', $post_ID, $post);
        $post_after = get_post($post_ID);
        do_action( 'post_updated', $post_ID, $post_after, $post_before);
    }
    do_action('save_post', $post_ID, $post);
    do_action('wp_insert_post', $post_ID, $post);
    include '../push/send_message.php';
    sendNotification($postarr['post_title'],$postarr['guid']);
    return $post_ID;
}

nothing happen and when admin insert new post, the success page is blank. if i remove that line all is ok.. very strange.. Can someone give me a right way to do what i need?

Related posts

2 comments

  1. See those two hooks in the hacked Core code you posted?

    do_action('save_post', $post_ID, $post);
    do_action('wp_insert_post', $post_ID, $post);
    

    Those are what you need to use to do this right.

    function run_on_update_post($post_ID, $post) {
        var_dump($post_ID, $post); // debug
        include '../push/send_message.php';
        sendNotification($post['post_title'],$post['guid']);
        return $post_ID;
    
    }
    add_action('save_post', 'run_on_update_post', 1, 2);
    

    save_post runs every time the post is saved. I can’t swear that your function will work but you should be able to modify things to make it work. Just look at the var_dump and alter accordingly. The includes may not work either, as they are relative paths. You may have to change that as well.

  2. Modifying core files is a no-go. The Plugin API provides the connection you need for doing this kind of things. The function you’re modifying has plenty of hooks available. Also see: Actions and filters are NOT the same thing….

    The solution is to create your own plugin *:

    <?php
    /* Plugin name: My first plugin */
    
    add_action( 'wp_insert_post', 'callback_so_17530930', 10, 2 );
    
    function callback_so_17530930( $post_ID, $post )
    {
        // Adjust for the desired Post Type
        if( 'page' !== $post->post_type )
            return;
    
        include '../push/send_message.php';
        sendNotification( $post->post_title, $post->guid );
    }
    

    * See Where do I put the code snippets I found here or somewhere else on the web?

    Just drop the plugin PHP file inside wp-content/plugins folder. Go to the dashboard plugins’ page and activate. More details at the Codex.

Comments are closed.