简体   繁体   中英

Get post id from inside posts_where wordpress

How can I get the post id from inside posts_where?

in my code below, $page_id = $wp_query->get_queried_object_id(); works on pages, but not posts. I've setup a second variable, $post_id, and would like to fill that with the post's id.

Here's my function/filter:

// Filter posts
    function ugrestriction_filter( $where, $wp_query )
    {
        global $wpdb, $post, $current_user, $wp_query;
        get_currentuserinfo();
        $user_id = $current_user->ID;
        $page_id = $wp_query->get_queried_object_id();
        $post_id = $wp_query->get_queried_object_id();

        $meta_key1    = '_ugrestriction';
        $meta_key1_value  = 'on';

        $postids=$wpdb->get_col( $wpdb->prepare( 
          "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = 'on'", "_ugrestriction"
        ) ); 


        //$postids = array("70", "1", "2", "3");

        if (in_array($post_id, $postids)) {
          $filter = 'on';
        } elseif (in_array($page_id, $postids)) {
          $filter = 'on';
        } 


        if ( $filter == 'on') {
          $where .= " AND ($wpdb->postmeta.meta_key = '_ugrestriction' AND $wpdb->postmeta.meta_value = 'on' AND " .  $wpdb->posts . " .post_author =". $user_id .")";
        }

            return $where;
    }

    add_filter( 'posts_where', 'ugrestriction_filter', 10, 2 );
// Filter posts
    function ugrestriction_filter( $where, $wp_query )
    {
        global $wpdb, $post, $current_user, $wp_query;
        get_currentuserinfo();
        $user_id = $current_user->ID;
        $page_id = $wp_query->get_queried_object_id();
        $post_id = $post->ID;

        $meta_key1    = '_ugrestriction';
        $meta_key1_value  = 'on';

        $postids=$wpdb->get_col( $wpdb->prepare( 
          "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = 'on'", "_ugrestriction"
        ) ); 


        //$postids = array("70", "1", "2", "3");

        if (in_array($post_id, $postids)) {
          $filter = 'on';
        } elseif (in_array($page_id, $postids)) {
          $filter = 'on';
        } 


        if ( $filter == 'on') {
          $where .= " AND ($wpdb->postmeta.meta_key = '_ugrestriction' AND $wpdb->postmeta.meta_value = 'on' AND " .  $wpdb->posts . " .post_author =". $user_id .")";
        }

            return $where;
    }

    add_filter( 'posts_where', 'ugrestriction_filter', 10, 2 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM