如何在触发的函数内执行脚本

时间:2018-06-19 13:47:39

标签: php wordpress function

function when_a_review_gets_submitted ($review, $post_id) {
// Do something
}

add_action('rwp_after_saving_review', 'when_a_review_gets_submitted', 11, 2);

我有这个WP_Query和循环,可以在有人留下评论的情况下更新父页面的每个子页面的自定义字段。

// Set up the objects needed
$hosting_provider_query = new WP_Query();
global $post;
$hosting_pagina_titel = $post->post_title;  
$search_all_pages = $hosting_provider_query->query(array(
    'post_type' => 'page',
    'post_status' => 'publish',
    //Only get pages where custom field 'name_hosting_provider' equals Page title
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => 'naam_hosting_provivder',
            'value' => $hosting_pagina_titel,
            'compare'   => '='
        ),

    ),
));

// Loop through all pages and find Page's children
$loop_through_all_child_pages = get_page_children( get_the_ID(), $search_all_pages );

// Loop through everything we got back
if(!empty($loop_through_all_child_pages)){
    foreach($loop_through_all_child_pages as $child_page){
        // get the ID of each childpage
        $get_child_page_ID = $child_page->ID;
        // get the ID of each parent page of the child pages
        $get_parent_page_ID = get_queried_object_id();
        // Get the average score from post_meta of the parent page
        $get_average_score = get_post_meta( $get_parent_page_ID, 'rwp_user_score', true );
        // update each custom field of the childs with the average score data from the post meta of parent page
        update_field('gemiddelde_score_hosting_provider', $get_average_score, $get_child_page_ID);
    }
}

如何在上述函数中正确执行此代码?

编辑

好吧,我弄清楚了,当我删除参数$ review和$ post_id时,该功能正常工作。当我删除添加操作时:

add_action('rwp_after_saving_review', 'when_a_review_gets_submitted', 11, 2);

并替换为:

add_action( 'template_redirect', 'when_a_review_gets_submitted' );

但是我认为这对于我想要达到的目标有些过高。如果我了解template_redirect,则每次使用该模板访问页面时,该函数就会执行该功能?我说得对吗?

因此,当我有900个子页面时,当访问带有该模板的页面时,它会更新每个自定义字段“ gemiddelde_score_hosting_provider”?那么,每次访问具有该模板的页面的次数都是900次?我对这个正确吗?

是否有一种方法只能从提交评论的父页面更新子级的自定义字段?

0 个答案:

没有答案