Добавить атрибут таксономии в шорткод Wordpress - PullRequest
1 голос
/ 04 апреля 2019

Я работаю над плагином WordPress, созданным для управления и отображения «расписания и расписания событий».

Вы можете добавить слоты событий (тип записи с именем «tcode_event») и назначить несколько определенных дней мероприятия (тип записи).с именем 'tcode_event-day')

Затем вы можете показать расписание событий с помощью короткого кода [2code-schedule-draw]

Я пытаюсь добавить возможность использования пользовательских таксономий в плагинечтобы можно было создать расписание с разными слотами и разными днями.

Например, моя цель может быть

 [2code-schedule-draw pacchetto="tax-slug"]

Показывать только дни и слоты событий, отмеченные таксономией.

Я использую ACF (Расширенное настраиваемое поле), чтобы создать свое настраиваемое поле в tcode_event и tcode_event-day, чтобы задать такие вещи, как местоположение, динамик и т. Д.

Я добавил пользовательскую таксономию в пользовательский тип записи,и это прекрасно работает.

// Setup 'pacchetti' taxonomy
add_action('init', function() {
$labels = array(
    'name'              => _x( 'Pacchetti', 'taxonomy general name' ),
    'singular_name'     => _x( 'Pacchetto', 'taxonomy singular name' ),
    'search_items'      => __( 'Search Pacchetti' ),
    'all_items'         => __( 'All Pacchetti' ),
    'parent_item'       => __( 'Parent Pacchetti' ),
    'parent_item_colon' => __( 'Parent Pacchetti:' ),
    'edit_item'         => __( 'Edit Pacchetti' ),
    'update_item'       => __( 'Update Pacchetti' ),
    'add_new_item'      => __( 'Add New Pacchetto' ),
    'new_item_name'     => __( 'New Pacchetti Name' ),
    'menu_name'         => __( 'Pacchetti' ),
);
$args = array(
    'hierarchical'      => true,
    'labels'            => $labels,
    'public'            => false,
    'show_ui'           => true,
    'show_admin_column' => false,
    'show_in_quick_edit'=> false,
    'show_tagcloud'     => false,
    'show_in_nav_menus' => false,
    'query_var'         => true,
    'rewrite'           => array( 'slug' => 'pacchetti' ),
);

register_taxonomy('pacchetti', array('tcode_event','tcode_event-day'), $args); });

Теперь я могу создавать и назначать свою собственную таксономию для элементов в моем типе записи.

Теперь яЯ застрял на том, как добавить фильтр в мою функцию шорткода, я пробовал несколько раз, но это не работает.Вот оригинальная функция шорткода:

// Initialize schedule shortcode 
add_shortcode('2code-schedule-draw', function() {
if (!class_exists('acf')) {
    return 'Could not find ACF. Please make sure it\'s installed or the 
\'Use embedded ACF\' option is selected in event-schedule settings.';
}

$postArray = array();

$posts = get_posts(array(
    'post_type' => 'tcode_event',
    'posts_per_page' => -1,
    'numberposts' => -1,
    'post_status' => 'publish',
    'suppress_filters' => false
));

if (!empty($posts)) {
    foreach($posts as $post) {
        setup_postdata($post);
// field_56b8f1ecb7820 is the key of the array to link the slot to the day
        if (have_rows('field_56b8f1ecb7820', $post->ID)) {
            while (have_rows('field_56b8f1ecb7820', $post->ID)) {
                the_row();

                $datePost = get_sub_field('event_date');

                if (!$datePost || $datePost->post_status !== 'publish') {
                    continue;
                }

                $time = get_sub_field('event_time');
                $time_ends = get_sub_field('event_time_ends');
                $time_end = date('Y-m-d ') . get_sub_field('event_time_end');
                $location = get_sub_field('event_location');
                $date = get_field('event_day_date', $datePost->ID);
                $date = str_replace('/', '-', $date);
                $date = new DateTime($date);
                $dateFormatted = $date->format('Y-m-d');

                $events = isset($postArray[$dateFormatted]) && isset($postArray[$dateFormatted]['events']) ? $postArray[$dateFormatted]['events'] : array();
                $events[] = array(
                    'time' => $time,
                    'time_ends' => $time_ends,
                    'time_end' => $time_end,
                    'event' => $post,
                    'location' => !empty($location) ? $location->slug : ''
                );

                usort($events, function($a, $b) {
                    $aTime = new DateTime($a['time']);
                    $bTime = new DateTime($b['time']);
                    return $aTime->getTimestamp() > $bTime->getTimestamp();
                });

                $locations = isset($postArray[$dateFormatted]) && isset($postArray[$dateFormatted]['locations']) ? $postArray[$dateFormatted]['locations'] : array();

                if (!empty($location)) {
                    $locationsSanitized = array_map(function($cat) {
                        return $cat->slug;
                    }, $locations);

                    if (!in_array($location->slug, $locationsSanitized)) {
                        $locations[] = $location;
                    }
                }

                usort($locations, function($a, $b) {
                    $aName = $a->name;
                    $bName = $b->name;

                    if (isset($a->term_order) && isset($b->term_order)) {
                        $aOrder = $a->term_order;
                        $bOrder = $b->term_order;

                        if ($aOrder !== $bOrder) {
                            return $aOrder < $bOrder;
                        }
                    }

                    return $aName < $bName;
                });

                $postArray[$dateFormatted] = array(
                    'day' => $datePost,
                    'events' => $events,
                    'locations' => $locations
                );
            }
        }
    }
    wp_reset_postdata();
}

ksort($postArray);
$postArray = array_values($postArray);

$imageFormat = get_field('2code_image_format', 'options');
$daysNum = get_field('2code_number_of_days', 'options');

ob_start();
require TCODE_ES_DIR . '/assets/templates/template.php';
return ob_get_clean();
});

Есть идеи о том, как внедрить мою собственную таксономию 'pacchetto' в шорткод и сделать так, чтобы она работала как фильтр?

Спасибо

1 Ответ

0 голосов
/ 08 апреля 2019

Вам необходимо разрешить использование шорткодов, см. Исправленный ниже код, обратите внимание, что я добавил откат к сообщениям, если не указан паччетто, чтобы отобразить что-то для возвращаемого цикла.Измените его на любое другое или установите значение по умолчанию для pacchetto, которое используется, если не указано в шорткоде:

function code_schedule_draw($atts) {
    extract(shortcode_atts(array(
        "pacchetto" => ''
    ), $atts));

    if (!class_exists('acf')) {
        return 'Could not find ACF. Please make sure it\'s installed or the 
        \'Use embedded ACF\' option is selected in event-schedule settings.';
    }

    $postArray = array();

    if(empty($pacchetto)) {
        $pacchetto = 'posts'
    }

    $posts = get_posts(array(
        'post_type' => $pacchetto,
        'posts_per_page' => -1,
        'numberposts' => -1,
        'post_status' => 'publish',
        'suppress_filters' => false
    ));

    if (!empty($posts)) {
        foreach($posts as $post) {
            setup_postdata($post);
            if (have_rows('field_56b8f1ecb7820', $post->ID)) {
                while (have_rows('field_56b8f1ecb7820', $post->ID)) {
                    the_row();

                    $datePost = get_sub_field('event_date');

                    if (!$datePost || $datePost->post_status !== 'publish') {
                        continue;
                    }

                    $time = get_sub_field('event_time');
                    $time_ends = get_sub_field('event_time_ends');
                    $time_end = date('Y-m-d ') . get_sub_field('event_time_end');
                    $location = get_sub_field('event_location');
                    $date = get_field('event_day_date', $datePost->ID);
                    $date = str_replace('/', '-', $date);
                    $date = new DateTime($date);
                    $dateFormatted = $date->format('Y-m-d');

                    $events = isset($postArray[$dateFormatted]) && isset($postArray[$dateFormatted]['events']) ? $postArray[$dateFormatted]['events'] : array();
                    $events[] = array(
                        'time' => $time,
                        'time_ends' => $time_ends,
                        'time_end' => $time_end,
                        'event' => $post,
                        'location' => !empty($location) ? $location->slug : ''
                    );

                    usort($events, function($a, $b) {
                        $aTime = new DateTime($a['time']);
                        $bTime = new DateTime($b['time']);
                        return $aTime->getTimestamp() > $bTime->getTimestamp();
                    });

                    $locations = isset($postArray[$dateFormatted]) && isset($postArray[$dateFormatted]['locations']) ? $postArray[$dateFormatted]['locations'] : array();

                    if (!empty($location)) {
                        $locationsSanitized = array_map(function($cat) {
                            return $cat->slug;
                        }, $locations);

                        if (!in_array($location->slug, $locationsSanitized)) {
                            $locations[] = $location;
                        }
                    }

                    usort($locations, function($a, $b) {
                        $aName = $a->name;
                        $bName = $b->name;

                        if (isset($a->term_order) && isset($b->term_order)) {
                            $aOrder = $a->term_order;
                            $bOrder = $b->term_order;

                            if ($aOrder !== $bOrder) {
                                return $aOrder < $bOrder;
                            }
                        }

                        return $aName < $bName;
                    });

                    $postArray[$dateFormatted] = array(
                        'day' => $datePost,
                        'events' => $events,
                        'locations' => $locations
                    );
                }
            }
        } wp_reset_postdata();
    }

    ksort($postArray);
    $postArray = array_values($postArray);

    $imageFormat = get_field('2code_image_format', 'options');
    $daysNum = get_field('2code_number_of_days', 'options');

    ob_start();
    require TCODE_ES_DIR . '/assets/templates/template.php';
    return ob_get_clean();

} add_shortcode("code-schedule-draw", "code_schedule_draw");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...