【问题标题】:Wordpress: using WP_query() and Advanced Custom Fields in function.phpWordpress:在 function.php 中使用 WP_query() 和高级自定义字段
【发布时间】:2015-04-24 21:28:31
【问题描述】:

我被主题卡住了。我编写了一个函数,它获取具有自定义类型“opt”的某些帖子字段(“高级自定义字段”插件用于字段),将其推送到数组中,将其编码为 json 并更新 .json 文件。

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 帖子和更简单的代码来实现...只有在我第二次按下“更新”按钮后才会写入文件

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

【问题讨论】:

  • 当您说“它根本不起作用”时,您是什么意思?它不写文件,还是写了但它是空的?
  • 它不写文件。
  • 您是否尝试过删除除 file_put_contents 之外的所有内容,然后只编写一个包含测试数据的文件?为了过滤掉一些内部 WP 进程干扰的可能性,我的意思是
  • Kai,我刚试过,它写了文件。数组是 $opt_array = array(NULL => 'zero',1 => 'one',2 => 'two');它在 .json 中写入 {"":"zero","1":"one","2":"two"}
  • 经过几次尝试后,我发现它确实写入了文件,但前提是我以某种方式更改了标题。如果我单独更改自定义字段中的数据,它不会更新 json。

标签: php hook custom-post-type wordpress


【解决方案1】:

acf/save_post 钩子可以解决问题

【讨论】:

    猜你喜欢
    • 2019-07-14
    • 2013-11-25
    • 1970-01-01
    • 2017-08-28
    • 2012-08-10
    • 2015-01-21
    • 2017-05-01
    • 1970-01-01
    • 2018-09-02
    相关资源
    最近更新 更多