2015-04-24 85 views
0

我被困在主题。我编写了一个函数,可以通过自定义类型'opt'获取特定的帖子字段('高级自定义字段'插件用于字段),将其推送到数组中,将其编码为json并更新.json文件。WordPress的:使用WP_query()和高级自定义字段在function.php

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) 
    ); 
} 

它完美,如果我打电话的功能,例如,主页上:

opt_update(); 

但我需要的是,当我发布到执行函数/更新“选择”自定义帖子。我试图使用该钩子:

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

...但它根本不起作用。虽然它不是挂钩的问题,如果我把不是“opt_update”的另一种功能,例如:

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

...它,因为它是应该给我发来电子邮件。 我错在哪里?

UPD:试图与一般的WordPress的职位和simplier代码做...还是只写入后,我按“更新”按钮第二次

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

当你说“它根本不起作用”你是什么意思?它不写入文件,或者它确实是空的? – d79

+0

它不写入文件。 – Lzhelenin

+0

您是否尝试删除除file_put_contents之外的所有内容,然后只用测试数据写入文件?为了过滤出一些内部WP进程干扰的可能性,我的意思是 –

回答

0

ACF/save_post钩做的文件技巧

相关问题