I got stuck with subj. I wrote a function that gets certain fields of posts (the 'advanced custom fields' plugin was used for the fields) with custom type 'opt', pushes it in an array, encodes it to json and updates .json file.
function opt_update() {
$args = array(
'post_type' => 'opt'
);
$opt_array = array();
$the_query = new WP_Query($args);
while ($the_query -> have_posts()): $the_query -> the_post();
$good_type_array = array();
while (have_rows('type')): the_row();
$type_name = get_sub_field('type_name');
array_push($good_type_array, $type_name);
endwhile;
array_push($opt_array, array(
'name' => get_the_title(),
'good_type' => $good_type_array,
'price' => get_field('price')
));
endwhile;
wp_reset_postdata();
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/blablabla/json/data.json', raw_json_encode($opt_array));
}
function raw_json_encode($input) {
return preg_replace_callback(
'/\\\\u([0-9a-zA-Z]{4})/',
function ($matches) {
return mb_convert_encoding(pack('H*',$matches[1]),'UTF-8','UTF-16');
},
json_encode($input)
);
}
It works perfectly if I call the function, for example, on the main page:
opt_update();
But what I need is to execute the function when I publish/update the 'opt' custom post. I tried to use that hook:
add_action('publish_opt', 'opt_update', 10, 2);
... but it doesn't work at all. Although it's not a problem of the hook, if I put instead of 'opt_update' an another function, for example:
add_action('publish_opt', 'mail_me', 10, 2);
... it sends me an e-mail message as it is supposed to. Where am I wrong?
UPD: Tried to do it with general wordpress posts and simplier code... still writes the file only after I press the 'update' button for the second time
function opt_update($ID, $post) {
$args = array(
'post_type' => 'post'
);
$opt_array = array();
$the_query = new WP_Query($args);
while ($the_query -> have_posts()): $the_query -> the_post();
array_push($opt_array, array(
'price' => get_field('price')
));
endwhile;
wp_reset_postdata();
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/blablabla/json/data.json', raw_json_encode($opt_array));
}
add_action('publish_post', 'opt_update', 10, 2);
答案 0 :(得分:0)
acf / save_post钩子可以解决这个问题