我如何从各种不同的自定义帖子类型的自定义字段中获取所有日期,并以升序在一个位置显示/列出它们?

时间:2019-09-26 作者:Graham Morteimer

我正在使用wordpress和pods构建一个web应用程序。我创建了不同的自定义帖子类型,如“project”、“task”和“material”,每个帖子都有不同的自定义日期字段。

我想在一个地方按升序列出所有这些自定义帖子类型中的所有日期。

到目前为止,我已经尝试了wp\\u query、get\\u post\\u meta和pods内置的查询功能,但这些功能都无法正常工作。

请帮我做这个,谢谢。

1 个回复
SO网友:Mark

get\\u post()和get\\u post\\u meta()应该可以收集数据,而array\\u multisort()应该能够按升序对数据进行排序。

    // Query the database to get the posts from your post types

    $project_args = array( \'post_type\' => \'projects\', "numberposts" => -1 );
    $task_args = array( \'post_type\' => \'tasks\', "numberposts" => -1 );
    $material_args = array( \'post_type\' => \'materials\', "numberposts" => -1 );

    $projects = get_posts( $project_args );
    $tasks = get_posts( $task_args );
    $materials = get_posts( $material_args );

    $list_items = array();
    $timestamps = array();

    // Loop through each set of posts adding the data you want to an array and their timestamp to another array
    foreach($projects as $project){ 
        array_push( $list_items, array( 
            \'name\' => $project->post_title, 
            \'date\' => get_post_meta( $project->ID, \'custom_date\'),
            )
        ); 
        array_push( $timestamps, strtotime( get_post_meta( $project->ID, \'custom_date\') ) );    
        }

    foreach($tasks as $task){ 
        array_push( $list_items, array( 
            \'name\' => $task-> post_title, 
            \'date\' => get_post_meta( $task->ID, \'custom_date\'),
            )
        ); 
        array_push( $timestamps, strtotime( get_post_meta( $task->ID, \'custom_date\') ) );       
        }

    foreach($materials as $material){ 
        array_push( $list_items, array( 
            \'name\' => $material-> post_title, 
            \'date\' => get_post_meta( $material->ID, \'custom_date\'), 
            )   
        );
        array_push( $timestamps, strtotime( get_post_meta( $material->ID, \'custom_date\') ) );       
        }

    //Sort both arrays based on the timestamp   
    $array_multisort( $timestamps, $list_items );

    //Output as you like
    print_r( $list_items );
对于多个日期,只需向foreach循环中添加额外的元字段,并确保将要排序的日期分配给$timestamps变量。

    foreach($materials as $material){ 
        array_push( $list_items, array( 
            \'name\' => $material-> post_title, 
            \'sort_date\' => get_post_meta( $material->ID, \'sort_date\'),
            \'date_1\' => get_post_meta( $material->ID, \'date_1\'),
            \'date_2\' => get_post_meta( $material->ID, \'date_2\'),
            \'date_3\' => get_post_meta( $material->ID, \'date_3\'), 
            )   
        );
        array_push( $timestamps, strtotime( get_post_meta( $material->ID, \'sort_date\') ) );     
        }