web-dev-qa-db-ja.com

WordPressのテーブルプレフィックスを考慮に入れる

以下のコードで、インストールごとに変わる可能性があるテーブルプレフィックスをどのように考慮すればよいでしょうか。 SQLクエリよりもそれを書くためのより良い方法はありますか?このようなときにテーブルのプレフィックスを指定していない、見逃した変数はありますか?

// setting posts with current date or older to draft
if (!wp_next_scheduled('sfn_expire_hook')){
    wp_schedule_event( time(), 'hourly', 'sfn_expire_hook');
}
add_action( 'sfn_expire_hook', 'sfn_show_expire');
function sfn_show_expire(){
    global $wpdb;
    $server_time = date('mdy');
    $result = $wpdb->get_results("SELECT * FROM GrandDn4wP_posts WHERE post_type = 'show' AND post_status = 'publish'");
    if( !empty($result)) foreach ($result as $a){
        $show_time = get_the_time('mdy', $a->ID);
        if ( $server_time > $show_time ){
           $my_post = array();
           $my_post['ID'] = $a->ID;
           $my_post['post_status'] = 'draft';
           wp_update_post( $my_post );
        }
    } // end foreach
}
2
curtismchale

このようにコードを書き直すことができます。

// setting posts with current date or older to draft
if (!wp_next_scheduled('sfn_expire_hook')){
    wp_schedule_event( time(), 'hourly', 'sfn_expire_hook');
}
add_action( 'sfn_expire_hook', 'sfn_show_expire');
function sfn_show_expire(){
    global $wpdb;
    $server_time = date('mdy');
    $result = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'show' AND post_status = 'publish'");
    if( !empty($result)) foreach ($result as $a){
        $show_time = get_the_time('mdy', $a->ID);
        if ( $server_time > $show_time ){
           $my_post = array();
           $my_post['ID'] = $a->ID;
           $my_post['post_status'] = 'draft';
           wp_update_post( $my_post );
        }
    } // end foreach
}

しかしそれを書くためのより良い方法は関数get_postsを使うことでしょう:

// setting posts with current date or older to draft
if (!wp_next_scheduled('sfn_expire_hook')){
    wp_schedule_event( time(), 'hourly', 'sfn_expire_hook');
}
add_action( 'sfn_expire_hook', 'sfn_show_expire');
function sfn_show_expire(){
    $server_time = date('mdy');
    $result = get_posts( array( post_type => 'show', post_status => 'publish' ) );
    if( !empty($result)) foreach ($result as $a){
        $show_time = get_the_time('mdy', $a->ID);
        if ( $server_time > $show_time ){
           $my_post = array();
           $my_post['ID'] = $a->ID;
           $my_post['post_status'] = 'draft';
           wp_update_post( $my_post );
        }
    } // end foreach
}
5
sorich87