Wordpress: using WP_query() and Advanced Custom Fields in function.php -


i got stuck subj. wrote function gets fields of posts (the 'advanced custom fields' plugin used fields) custom type 'opt', pushes in array, encodes json , 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 if call function, example, on main page:

opt_update(); 

but need execute function when publish/update 'opt' custom post. tried use hook:

add_action('publish_opt', 'opt_update', 10, 2); 

... doesn't work @ all. although it's not problem of hook, if put instead of 'opt_update' function, example:

 add_action('publish_opt', 'mail_me', 10, 2); 

... sends me e-mail message supposed to. wrong?

upd: tried general wordpress posts , simplier code... still writes file after press 'update' button 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); 

acf/save_post hook trick


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -