WP hook function 'save_post'

2019-08-30 05:52发布

问题:

Was trying to use the save_post hook to create a html file, every time a file is saved.

But after editing the content and on trying to update an existing post, wp returns the message

"Not Found Apologies, but the page you requested could not be found. Perhaps searching will help."

The post is neither updated in WP, nor the function 'write_single_post' creates a html file as intended. Is there anything wrong with the way the function and the hook is used.....

function write_single_post($post_ID)  
{
global $folder;

 $file = $folder.$post_ID.".html";

$fh = fopen($file, 'w') or die("can't open file");
$string ="data goes here\n";
echo (fwrite($fh,$string))?"written":"not writtern";
fclose($fh);
}

do_action('save_post','write_single_post',$post_ID);

回答1:

do_action() creates a new hook. add_action() uses an existing hook. For example,

function write_single_post($post_ID)  
{
 global $folder;

 $file = $folder.$post_ID.".html";

 $fh = fopen($file, 'w') or die("can't open file");
 $string ="data goes here\n";
 echo (fwrite($fh,$string))?"written":"not writtern";
 fclose($fh);
}

add_action('save_post','write_single_post');

it only needs the hook & your function in this case. The post ID is passed in automatically.



标签: php wordpress