%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home/maraton/maraton.eco-n-tech.co.uk/wp-content/themes/maraton/
Upload File :
Create Path :
Current File : //home/maraton/maraton.eco-n-tech.co.uk/wp-content/themes/maraton/functions.php

<?php
/**
 * Timber starter-theme
 * https://github.com/timber/starter-theme
 *
 * @package  WordPress
 * @subpackage  Timber
 * @since   Timber 0.1
 */


/**
 * This ensures that Timber is loaded and available as a PHP class.
 * If not, it gives an error message to help direct developers on where to activate
 */
if (!class_exists('Timber')) {

    add_action(
        'admin_notices',
        function () {
            echo '<div class="error"><p>Timber not activated. Make sure you activate the plugin in <a href="' . esc_url(admin_url('plugins.php#timber')) . '">' . esc_url(admin_url('plugins.php')) . '</a></p></div>';
        }
    );

    add_filter(
        'template_include',
        function ($template) {
            return get_stylesheet_directory() . '/static/no-timber.html';
        }
    );
    return;
}

require_once('includes/dimox_breadcrumbs.php');
// require_once('includes/cf7_data_attributes.php');

/**
 * Sets the directories (inside your theme) to find .twig files
 */
Timber::$dirname = array('templates', 'views');

/**
 * By default, Timber does NOT autoescape values. Want to enable Twig's autoescape?
 * No prob! Just set this value to true
 */
Timber::$autoescape = false;


/**
 * We're going to configure our theme inside of a subclass of Timber\Site
 * You can move this to its own file and include here via php's include("MySite.php")
 */
class StarterSite extends Timber\Site
{
    /** Add timber support. */
    public function __construct()
    {
        add_action('after_setup_theme', array($this, 'theme_supports'));
        add_filter('timber/context', array($this, 'add_to_context'));
        add_filter('timber/twig', array($this, 'add_to_twig'));

        add_filter('mce_buttons_2', function ($buttons) {
            array_unshift($buttons, 'styleselect');
            return $buttons;
        });
        add_filter('tiny_mce_before_init', array($this, 'tiny_mce_before_init'));

        add_action('init', array($this, 'register_post_types'));
        add_action('init', array($this, 'register_taxonomies'));
        add_action('init', array($this, 'biblioteket_rewrite_rules'), 11, 0);
        add_action('wp_enqueue_scripts', array($this, 'loadScripts'));

        add_filter( 'query_vars', array($this, 'register_year_filter_query_var') );

        add_action('admin_enqueue_scripts', array($this, 'loadAdminScripts'));
        add_action('admin_menu', array($this, 'add_admin_submenu_pages'));

        add_action('wp_ajax_nopriv_load_more_posts', array($this, 'load_more_posts_callback'));
        add_action('wp_ajax_load_more_posts', array($this, 'load_more_posts_callback'));

        add_action('pre_get_posts', array($this, 'pre_get_posts_filter'), 1);

        wpcf7_add_form_tag('arrow', array($this, 'arrow_shortcode'));
        add_shortcode('arrow', array($this, 'arrow_shortcode'));

        $this::loadBlocks();

        parent::__construct();
    }

    public function biblioteket_rewrite_rules() {
        add_rewrite_rule(
            'biblioteket/([0-9]{4})/([^/]+)/?$',
            array(
                'year_filter' => '$matches[1]',
                'season_filter' => '$matches[2]',
                'post_type'   => 'biblioteket',
            ),
            'top'
        );
    }

    public function register_year_filter_query_var($vars) {
        $vars[] = 'year_filter';
        $vars[] = 'season_filter';
        return $vars;
    }

    public function arrow_shortcode($atts) {
        $arrow = '<div class="shortcode-arrow">' . display_svg('/dist/img/arrow-right-big.svg') . '</div>';

        return $arrow;
    }

    // Custom formats
    public function tiny_mce_before_init($settings)
    {
        $style_formats = array(
            array(
                'title' => 'Button',
                'selector' => 'a',
                'classes' => 'button'
            ),
            array(
                'title' => 'Checks list',
                'block' => 'div',
                'classes' => 'checks-list',
                'wrapper' => true
            ),
            array(
                'title' => 'Animations',
                'items' => array(
                    array(
                        'title' => 'Fade in',
                        'selector' => '*',
                        'classes' => 'animate__delay-1s animate__fadeIn animate__animated'
                    ),
                    array(
                        'title' => 'Fade in left',
                        'selector' => '*',
                        'classes' => 'animate__delay-1s animate__animated animate__fadeInLeft'
                    )
                )
            )
        );

        $settings['style_formats'] = json_encode($style_formats);
        return $settings;
    }

    // function to load all blocks from the blocks folder
    public function loadBlocks()
    {
        $blocks = glob(get_template_directory() . '/blocks/*', GLOB_ONLYDIR);
        foreach ($blocks as $block) {
            $blockName = basename($block);
            require_once(get_template_directory() . '/blocks/' . $blockName . '/index.php');
        }
    }

    /** This is where you can register custom post types. */
    public function register_post_types()
    {

    }

    /** This is where you can register custom taxonomies. */
    public function register_taxonomies()
    {

    }

    public function loadScripts()
    {
        wp_enqueue_style('ofelia-font', 'https://use.typekit.net/vtx0ecq.css', array(), null);

        wp_enqueue_style('main-style', get_template_directory_uri() . '/dist/app.css', array(), null);

        wp_enqueue_script('jquery');

        // wp_enqueue_script( 'gsap', 'https://cdn.jsdelivr.net/npm/gsap@3.0.1/dist/gsap.min.js', array(), '', true );

        wp_enqueue_script('main-app', get_template_directory_uri() . '/dist/app.js', array(), null);


        wp_localize_script('main-app', 'theme', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
        ));
    }

    public function loadAdminScripts()
    {
        wp_enqueue_style('admin-main-style', get_template_directory_uri() . '/dist/admin.css', array(), null);

        wp_enqueue_script('admin-app', get_template_directory_uri() . '/dist/admin.js', array(), null);
    }

    public function get_modified_file($file)
    {
        $dir = __DIR__;
        $filename = $dir . $file;
        if (file_exists($filename)) {
            return filemtime($filename);
        }

    }


    /** This is where you add some context
     *
     * @param string $context context['this'] Being the Twig's {{ this }}.
     */
    public function add_to_context($context)
    {
        $context['options'] = get_fields('options');
        $context['menu'] = new \Timber\Menu('primary_navigation');
        $context['menu_for_standart_pages'] = new \Timber\Menu('standart_pages');
        $context['page_id'] = get_queried_object_id();
        $context['site'] = $this;
        $context['breadcrumbs'] = dimox_breadcrumbs();
        $context['page_for_posts_id'] = get_option('page_for_posts');
        $context['page_for_posts'] = get_permalink(get_option('page_for_posts'));
        $context['posts_per_page'] = get_option('posts_per_page');
        $context['get_current_url'] = Timber\URLHelper::get_current_url();
        $context['header_style'] = get_field('header_style', get_queried_object_id());
        $context['head_scripts'] = get_field('head_scripts', get_queried_object_id());

        // Popup
        $context['popup']['title'] = get_field('popup_title', 'options');
        $context['popup']['description'] = get_field('popup_description', 'options');
        $context['popup']['form'] = get_field('popup_form', 'options');

        return $context;
    }

    public function theme_supports()
    {

        load_theme_textdomain('maraton', get_template_directory() . '/languages');


        // Add default posts and comments RSS feed links to head.
        add_theme_support('automatic-feed-links');

        /*
         * Let WordPress manage the document title.
         * By adding theme support, we declare that this theme does not use a
         * hard-coded <title> tag in the document head, and expect WordPress to
         * provide it for us.
         */
        add_theme_support('title-tag');

        /*
         * Enable support for Post Thumbnails on posts and pages.
         *
         * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
         */
        add_theme_support('post-thumbnails');

        /*
         * Switch default core markup for search form, comment form, and comments
         * to output valid HTML5.
         */
        add_theme_support(
            'html5',
            array(
                'comment-form',
                'comment-list',
                'gallery',
                'caption',
            )
        );

        /*
         * Enable support for Post Formats.
         *
         * See: https://codex.wordpress.org/Post_Formats
         */
        add_theme_support(
            'post-formats',
            array(
                'aside',
                'image',
                'video',
                'quote',
                'link',
                'gallery',
                'audio',
            )
        );

        register_nav_menus([
            'primary_navigation' => 'Primary Navigation',
            'standart_pages' => 'Standart Pages'
        ]);

        add_theme_support('menus');

        if (function_exists('acf_add_options_page')) {
            acf_add_options_page(array(
                'page_title' => 'Theme options',
                'icon_url' => 'dashicons-admin-settings'
            ));
        }
    }

    /** This Would return 'foo bar!'.
     *
     * @param string $text being 'foo', then returned 'foo bar!'.
     */
    public function myfoo($text)
    {
        $text .= ' bar!';
        return $text;
    }

    /** This is where you can add your own functions to twig.
     *
     * @param string $twig get extension.
     */
    public function add_to_twig($twig)
    {
        $twig->addExtension(new Twig\Extension\StringLoaderExtension());
        $twig->addFilter(new Twig\TwigFilter('myfoo', array($this, 'myfoo')));
        $twig->addFunction(new Timber\Twig_Function('cms_is_in_menu', array($this, 'cms_is_in_menu_callback')));


        // $twig->addFilter(new Twig\TwigFilter( 'is_current_url', function ($link) {
        // 	return (Timber\URLHelper::get_current_url() == $link) ? true : false;
        // }));

        // Display SVG function
        $twig->addFunction(new Timber\Twig_Function('display_svg', function ($svg) {
            $svg = get_template_directory() . $svg;
            if (file_exists($svg)) {
                return file_get_contents($svg);
            }
        }));

        // Retrive season name by month
        $twig->addFunction(new Timber\Twig_Function('get_season_name', function ($month) {
            $seasons = [
                __('Winter') => [12, 1, 2],
                __('Spring') => [3, 4, 5],
                __('Summer') => [6, 7, 8],
                __('Autumn') => [9, 10, 11]
            ];

            foreach ($seasons as $key => $value) {
                if (in_array($month, $value)) {
                    return $key;
                }
            }
        }));

        return $twig;
    }

    public function cms_is_in_menu_callback($theme_location = null, $object_id = null)
    {

        $theme_locations = get_nav_menu_locations();

        $menu_obj = get_term($theme_locations[$theme_location], 'nav_menu');

        $menu = $menu_obj->term_id;


        $menu_object = wp_get_nav_menu_items(esc_attr($menu));

        if (!$menu_object)
            return false;

        $menu_items = wp_list_pluck($menu_object, 'object_id');

        if (!$object_id) {
            global $post;
            $object_id = get_queried_object_id();
        }

        return in_array((int)$object_id, $menu_items);

    }

    public function add_admin_submenu_pages()
    {
        $joinus = get_pages(array(
            'meta_key' => '_wp_page_template',
            'meta_value' => 'page-joinus.php'
        ));

        if ($joinus) {
            add_submenu_page('edit.php?post_type=joinus', 'Join us (page)', 'Join us (page)', 'manage_options', 'post.php?post=' . $joinus[0]->ID . '&action=edit', '', 99);
        }

        $solutions = get_pages(array(
            'meta_key' => '_wp_page_template',
            'meta_value' => 'page-solutions.php'
        ));

        if ($solutions) {
            add_submenu_page('edit.php?post_type=solutions', 'Solutions (page)', 'Solutions (page)', 'manage_options', 'post.php?post=' . $solutions[0]->ID . '&action=edit', '', 99);
        }


        $assets = get_pages(array(
            'meta_key' => '_wp_page_template',
            'meta_value' => 'page-assets.php'
        ));

        if ($assets) {
            add_submenu_page('edit.php?post_type=assets', 'Assets (page)', 'Assets (page)', 'manage_options', 'post.php?post=' . $assets[0]->ID . '&action=edit', '', 99);
        }

    }

    public function load_more_posts_callback()
    {
        if ($_POST) {


            $context = Timber::context();


            $offset = intval($_POST['countPosts']);
            $reload = $_POST['reload'] == 'true' ? true : false;
            $post_type = $_POST['postType'];

            if ($post_type == 'assets') {
                $step = intval(get_field('load_more_assets_quantity', 'options'));
            }

            if ($post_type == 'post') {
                $step = intval(get_field('load_more_posts_quantity', 'options'));
            }

            if ($post_type == 'assets') {
                $tax_query = [];
                $meta_query = [];

                if (array_key_exists('target_group_c', $_POST) && array_key_exists('asset_locations_c', $_POST)) {
                    $tax_query['relation'] = 'AND';
                }

                if (array_key_exists('target_group_c', $_POST)) {
                    $tax_query[] = [
                        'taxonomy' => 'target_group',
                        'field' => 'id',
                        'terms' => array(intval($_POST['target_group_c'])),
                    ];
                }

                if (array_key_exists('asset_locations_c', $_POST)) {
                    $tax_query[] = [
                        'taxonomy' => 'asset_locations',
                        'field' => 'id',
                        'terms' => array(intval($_POST['asset_locations_c'])),
                    ];
                }

                if (array_key_exists('status', $_POST)) {
                    $meta_query[] = array(
                        'key' => 'status',
                        'value' => $_POST['status']
                    );
                }

            }


            if ($post_type == 'post') {
                $args = array(
                    'numberposts' => -1,
                    'post_type' => 'post',
                    'orderby' => 'date',
                    'order' => 'DESC'
                );
                if (array_key_exists('category', $_POST)) {
                    $args['category'] = intval($_POST['category']);
                }
            }

            if ($post_type == 'assets') {
                $args = array(
                    'numberposts' => -1,
                    'post_type' => 'assets',
                    'orderby' => 'menu_order',
                    'order' => 'ASC'
                );
                if ($tax_query) {
                    $args['tax_query'] = $tax_query;
                }

                if ($meta_query) {
                    $args['meta_query'] = $meta_query;
                }


            }

            $total = get_posts($args);

            $context['posts'] = [];

            if ($post_type == 'post') {
                $args = array(
                    'offset' => $offset,
                    'numberposts' => $step,
                    'post_type' => 'post',
                    'orderby' => 'date',
                    'order' => 'DESC'
                );
                if (array_key_exists('category', $_POST)) {
                    $args['category'] = intval($_POST['category']);
                }
            }

            if ($post_type == 'assets') {
                $args = array(
                    'offset' => $reload ? 0 : $offset,
                    'numberposts' => $reload ? intval(get_field('homepage_assets_quantity', 'options')) : $step,
                    'post_type' => 'assets',
                    'orderby' => 'menu_order',
                    'order' => 'ASC'
                );

                if ($tax_query) {
                    $args['tax_query'] = $tax_query;
                }

                if ($meta_query) {
                    $args['meta_query'] = $meta_query;
                }


            }

            $posts = get_posts($args);


            $out = '';


            foreach ($posts as $post) {
                $context['post'] = Timber::get_post($post->ID);
                $out .= Timber::compile('tease-' . $post_type . '.twig', $context);
            }

            if (!$out && $reload) $out = '<div id="load-more--scroll"></div><h4 class="no-posts">Sorry, no assets match your request...</h4>';;

            if ($reload) {
                $remove_button = count($total) <= intval(get_field('homepage_assets_quantity', 'options'));
            } else {
                $remove_button = count($total) <= $offset + $step;
            }


            echo json_encode(['code' => 200, 'remove_button' => $remove_button, 'out' => $out]);

        }

        exit();
    }

    public function pre_get_posts_filter($query)
    {

        // Выходим, если это админ-панель или не основной запрос.
        if (is_admin() || !$query->is_main_query() || empty( get_query_var( 'post_type' ) ) || get_query_var( 'post_type' ) !== 'biblioteket')
            return;

        if ($query->is_post_type_archive('biblioteket')) {
            $query->set( 'posts_per_page', 7 );
        }

        if ( ! empty( get_query_var( 'year_filter' ) ) ) {
            set_query_var( 'year', get_query_var( 'year_filter' ) );
            // set date query to filter by month
            $season = array(
                'winter' => array(
                    'after' => '12',
                    'before' => '03',
                ),
                'spring' => array(
                    'after' => '03',
                    'before' => '06',
                ),
                'summer' => array(
                    'after' => '06',
                    'before' => '09',
                ),
                'autumn' => array(
                    'after' => '09',
                    'before' => '12',
                )
            );

            $query->set( 'date_query', array(
                array(
                    'after'  => get_query_var( 'year_filter' ) . '-'.$season[get_query_var( 'season_filter' )]['after'].'-01',
                    'before'  => get_query_var( 'year_filter' ) . '-'.$season[get_query_var( 'season_filter' )]['before'].'-01'
                )
            ) );
        }
    }


}

new StarterSite();

// Helpers
function display_svg ($svg) {
    $svg = get_template_directory() . $svg;
    if (!file_exists($svg)) return;

    return file_get_contents($svg);
}


////// ci test

Zerion Mini Shell 1.0