我使用的插件包含以下代码:
$download = array(
\'post_title\' => $title,
\'post_content\' => \'\',
\'post_status\' => \'publish\',
\'post_author\' => get_current_user_id(),
\'post_type\' => \'dlm_download\'
);
$download_id = wp_insert_post( $download );
if ( $download_id ) {
// Meta
update_post_meta( $download_id, \'_featured\', \'no\' );
update_post_meta( $download_id, \'_members_only\', \'no\' );
我想创建自己的插件,以便在所有情况下将\\u members\\u only值设置为yes。到目前为止,我得到的代码是:
function dlmc_members_only_default( $check, $object_id, $meta_key, $meta_value, $prev_value )
{
// Avoid infinite recursion:
remove_filter( current_filter(), __FUNCTION__ );
// Modify the meta value;
$meta_value = "yes";
// Update the modified value.
update_post_meta( $object_id, $meta_key, $meta_value, $prev_value );
// Return something else than null
return true;
}
add_filter( \'update_post_metadata\', \'dlmc_members_only_default\', 11, 5 );
不幸的是,这似乎让wordpress陷入了一个无限循环,尽管有一行人打算阻止它。有没有更好的方法来实现我的目标?谢谢
最合适的回答,由SO网友:Ismail 整理而成
如果您钩住update_post_meta()
函数并仍在回调中使用此函数,这将导致一个循环,该循环可能以超时结束。。
根据评论:
add_action("wp_insert_post", function( $post_ID ) {
if ( ! $post_data = get_post( $post_ID ) ) return;
// try to make this run only once needed ( from the question, the content is empty and cPT is dlm_download )
if ( "dlm_download" == $post_data->post_type && ! $post_data->post_content ) {
update_option( "dlm_download_members_only_yes", $post_data->ID );
}
return;
}, 10);
add_action("init", function() {
if ( $pid = (int) get_option( "dlm_download_members_only_yes" ) ) {
update_post_meta( $pid, "_members_only", "yes" );
delete_option( "dlm_download_members_only_yes" );
} return;
});
init
钩子总是存在的(页面加载、AJAX等),所以这应该总是有效的,并且对多个条目也有效。。