0

I want to edit the content before save to database for the first time only when add a new post, so i check the path if it's at the post-new.php i want to apply the filter, but it's not working. anyone know how to solve this ?

$pagePath = parse_url( $_SERVER['REQUEST_URI'] );
$pagePath = $pagePath['path'];
$pagePath = substr($pagePath, 1);

if($pagePath === 'wp-admin/post-new.php'){
    function my_filter_function_name( $content ) {
        return $content . 'text before save to db';
    }

    add_filter( 'content_save_pre', 'my_filter_function_name', 10, 1 );
}
1
  • Use $page_now or current_screen() to know which page is running, to be sure that the filter can fires.
    – Benoti
    Commented Nov 22, 2016 at 11:08

2 Answers 2

0

No need to write this too much code.

$pagePath = parse_url( $_SERVER['REQUEST_URI'] );
$pagePath = $pagePath['path'];
$pagePath = substr($pagePath, 1);

you can easily get current page path by calling global variable $pagenow.

global $pagenow; // return 'post-new.php'

Instead of using content_save_pre filter you can do this same with wp_insert_post_data filter more easily. try out this.

add_filter( 'wp_insert_post_data', 'appendContent', 99, 2 );

function appendContent( $data, $postarr ) {  

       // Retrieve referer path of current page through wp_get_referer(). 
       $referer = basename( wp_get_referer() );  // post-new.php

       if ( ! wp_is_post_revision( $postarr['ID'] ) && $referer == 'post-new.php' ) {

             $data['post_content'] = $data['post_content'] . ' text before save to db';
        }
    return $data;
}

wp_insert_post_data is called by the wp_insert_post function prior to inserting into or updating the database.

0
0

I did not understand your logic to check if it is first time. If your logic is correct, if condition should be inside the filter function.

$pagePath = parse_url( $_SERVER['REQUEST_URI'] );
$pagePath = $pagePath['path'];
$pagePath = substr($pagePath, 1);


function my_filter_function_name( $content ) {
    if($pagePath === 'wp-admin/post-new.php')
    {
        return $content . 'text before save to db';
    }
}

add_filter( 'content_save_pre', 'my_filter_function_name', 10, 1 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.