admin管理员组

文章数量:1417662

I'm trying to make a function (without sucess) that modify a specific part of the post content before first publish.

function modifyOnPost()
{

    add_action( 'the_post', 'modifying' );
    function modifying( $post ) {
    $post->content = str_replace( "original text", "modified text", $post->post_content );
    }
}
add_action('publish_post', 'modifyOnPost');

Nothing happens, not even a error code.

Any help pointing to the right way would be appreciated.

I'm trying to make a function (without sucess) that modify a specific part of the post content before first publish.

function modifyOnPost()
{

    add_action( 'the_post', 'modifying' );
    function modifying( $post ) {
    $post->content = str_replace( "original text", "modified text", $post->post_content );
    }
}
add_action('publish_post', 'modifyOnPost');

Nothing happens, not even a error code.

Any help pointing to the right way would be appreciated.

Share Improve this question edited Aug 1, 2019 at 11:21 Pratik Patel 1,1111 gold badge11 silver badges23 bronze badges asked Aug 1, 2019 at 11:17 user3466661user3466661 11 bronze badge 1
  • I would avoid declaring functions inside functions, also neither of those hooks will do what you need them to do, the_post actually runs on the frontend at the start of each loop iteration – Tom J Nowell Commented Aug 1, 2019 at 11:47
Add a comment  | 

1 Answer 1

Reset to default 0

You should use save_post like the following:

function modifyOnPost( $post_id ) {
   $post = get_post($post_id);
   //do stuff here before your post is created or updated
}
add_action( 'save_post', 'modifyOnPost' );

Read more here.

Update:

To give a deeper solution you could use wp_update_post( $post, $wp_error ); inside the modifyOnPost block to manipulate your post data.

本文标签: functionsModify content inside post before first publish