Susobhan Das
Susobhan Das

Reputation: 1144

PHP function in wordpress removing slashes

I am working on Wordpress theme , the theme stores custom Javascript to the database by update_post_meta() hook as post metadata. But the problem is that, the PHP file_get_contents() is removing backslashes abnormally.

The PHP function I am using in functions.php in Wordpress

function add_template($post_id){

    $custom_javascript = get_post_meta( $post->ID, 'custom_javascript', true );

    $template_js = file_get_contents(get_template_directory_uri(). '/template/prism.js');

    update_post_meta( $post_id, 'custom_javascript',  $template_js );
}

add_action( 'save_post', 'add_template' );

One Error:

Original Javascript: (^|[^\\])\/\*[\s\S]*?(?:\*\/|$)

Modified Javascript: (^|[^\])/*[sS]*?(?:*/|$)

How to get rid of this issue? Any help/suggestion would be appreciated.

Upvotes: 1

Views: 1192

Answers (1)

Susobhan Das
Susobhan Das

Reputation: 1144

Just need to add addslashes() function.

So, the working PHP code for wordpress would be -

function add_template($post_id){

    $custom_javascript = get_post_meta( $post->ID, 'custom_javascript', true );

    $template_js = file_get_contents(get_template_directory_uri(). '/template/prism.js');

    update_post_meta( $post_id, 'custom_javascript',  addslashes($template_js ));
}

add_action( 'save_post', 'add_template' );

Or in Short

function add_template($post_id){

    $custom_javascript = get_post_meta( $post->ID, 'custom_javascript', true );

   update_post_meta( $post_id, 'custom_javascript',  addslashes(file_get_contents(get_template_directory_uri(). '/template/prism.js' )));
}

add_action( 'save_post', 'add_template' );

Upvotes: 2

Related Questions