function get_monthly_archive_array()
{
$years = [];
$years_args = [
'type' => 'monthly',
'format' => 'custom',
'before' => '',
'after' => '|',
'echo' => false,
'post_type' => 'post',
// 'order' => 'ASC',
];
// Get Years
$years_content = wp_get_archives($years_args);
if (!empty($years_content)) {
$years_arr = explode('|', $years_content);
// Remove empty whitespace item from array.
$years_arr = array_filter($years_arr, function ($item) {
return trim($item) !== '';
});
foreach ($years_arr as $year_item) {
$year_row = trim($year_item);
preg_match('/href=["\']?([^"\'>]+)["\']>(.+)<\/a>/', $year_row, $year_vars);
if (!empty($year_vars) && is_array($year_vars)) {
$year_url = !empty($year_vars[1]) ? $year_vars[1] : ''; // Eg: http://demo.com/2021/11/
$parts = parse_url($year_url);
$path = !empty($parts['path']) ? $parts['path'] : '';
$years[] = [
'name' => $year_vars[2], // Eg: November 2021
'slug' => $path // Eg: /2021/11/ , so that we can prefix o suffix our own URL.
];
}
}
}
return $years;
}
add_action('graphql_register_types', 'xyz_register_archive_type');
function xyz_register_archive_type()
{
register_graphql_object_type('XYZArchiveDate', [
'description' => __("Archive liks", 'xyz'),
'fields' => [
'name' => [
'type' => 'String',
'description' => __('The name of the archive date', 'dcc'),
],
'slug' => [
'type' => 'String',
'description' => __('The slug value of archive', 'dcc'),
],
],
]);
}
add_action('graphql_register_types', 'xyz_extend_archive_wpgraphql_schema');
function xyz_extend_archive_wpgraphql_schema()
{
register_graphql_field('RootQuery', 'archiveDates', [
'type' => ['list_of' => 'XYZArchiveDate'],
'description' => __('Returns archive dates', 'xyz'),
'resolve' => function () {
return get_monthly_archive_array();
}
]);
};
Reply
You must be logged in to post a comment.