最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - get_posts shows current post, not defined posts with args

programmeradmin0浏览0评论

I want to show defined posts but get_posts shows current post without use definition in args.Why, how to solve it? what is difference between get_posts and wp query? thanks

add_action( 'template_redirect', 'check_shop' );
function check_shop()
{
    if (is_shop() ) {
            $args1 = array(
                'post_author' => 'admin',
                'post_type' => 'page',
            );
            $post_types1 = get_posts( $args1, 'objects' );
            foreach ($post_types1 as $post_type1) {
                setup_postdata( $post_type1 );
                if (!empty($post_type1->post_content)) {
                    add_action('woocommerce_before_shop_loop_item_title', function() {
                        global $post_type1;
                        the_title();
                        echo get_the_title($post_type1->ID);
                        echo $post_type1;
                        echo $post_type1->post_content;
                        echo "denemeee yazısı";
                    }, 1);
                }
            }
        wp_reset_postdata();
    }
}

I want to show defined posts but get_posts shows current post without use definition in args.Why, how to solve it? what is difference between get_posts and wp query? thanks

add_action( 'template_redirect', 'check_shop' );
function check_shop()
{
    if (is_shop() ) {
            $args1 = array(
                'post_author' => 'admin',
                'post_type' => 'page',
            );
            $post_types1 = get_posts( $args1, 'objects' );
            foreach ($post_types1 as $post_type1) {
                setup_postdata( $post_type1 );
                if (!empty($post_type1->post_content)) {
                    add_action('woocommerce_before_shop_loop_item_title', function() {
                        global $post_type1;
                        the_title();
                        echo get_the_title($post_type1->ID);
                        echo $post_type1;
                        echo $post_type1->post_content;
                        echo "denemeee yazısı";
                    }, 1);
                }
            }
        wp_reset_postdata();
    }
}
Share Improve this question asked Jan 26, 2021 at 13:12 Faruk rızaFaruk rıza 982 silver badges11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

As documented:

setup_postdata() does not assign the global $post variable so it’s important that you do this yourself. Failure to do so will cause problems with any hooks that use any of the above globals in conjunction with the $post global, as they will refer to separate entities.

So you need to do this:

global $post; // This...

foreach ($post_types1 as $post_type1) {
    $post = $post_type1; // ...and this.

    setup_postdata( $post_type1 );

    // etc.
}

wp_reset_postdata();
发布评论

评论列表(0)

  1. 暂无评论