/**
* Theme functions and definitions
*
* @package HelloElementor
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly.
}
define('HELLO_ELEMENTOR_VERSION', '3.1.0');
if (!isset($content_width)) {
$content_width = 800; // Pixels.
}
if (!function_exists('hello_elementor_setup')) {
/**
* Set up theme support.
*
* @return void
*/
function hello_elementor_setup()
{
if (is_admin()) {
hello_maybe_update_theme_version_in_db();
}
if (apply_filters('hello_elementor_register_menus', true)) {
register_nav_menus(['menu-1' => esc_html__('Header', 'hello-elementor')]);
register_nav_menus(['menu-2' => esc_html__('Footer', 'hello-elementor')]);
}
if (apply_filters('hello_elementor_post_type_support', true)) {
add_post_type_support('page', 'excerpt');
}
if (apply_filters('hello_elementor_add_theme_support', true)) {
add_theme_support('post-thumbnails');
add_theme_support('automatic-feed-links');
add_theme_support('title-tag');
add_theme_support(
'html5',
[
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
'script',
'style',
]
);
add_theme_support(
'custom-logo',
[
'height' => 100,
'width' => 350,
'flex-height' => true,
'flex-width' => true,
]
);
/*
* Editor Style.
*/
add_editor_style('classic-editor.css');
/*
* Gutenberg wide images.
*/
add_theme_support('align-wide');
/*
* WooCommerce.
*/
if (apply_filters('hello_elementor_add_woocommerce_support', true)) {
// WooCommerce in general.
add_theme_support('woocommerce');
// Enabling WooCommerce product gallery features (are off by default since WC 3.0.0).
// zoom.
add_theme_support('wc-product-gallery-zoom');
// lightbox.
add_theme_support('wc-product-gallery-lightbox');
// swipe.
add_theme_support('wc-product-gallery-slider');
}
}
}
}
add_action('after_setup_theme', 'hello_elementor_setup');
function hello_maybe_update_theme_version_in_db()
{
$theme_version_option_name = 'hello_theme_version';
// The theme version saved in the database.
$hello_theme_db_version = get_option($theme_version_option_name);
// If the 'hello_theme_version' option does not exist in the DB, or the version needs to be updated, do the update.
if (!$hello_theme_db_version || version_compare($hello_theme_db_version, HELLO_ELEMENTOR_VERSION, '<')) {
update_option($theme_version_option_name, HELLO_ELEMENTOR_VERSION);
}
}
if (!function_exists('hello_elementor_display_header_footer')) {
/**
* Check whether to display header footer.
*
* @return bool
*/
function hello_elementor_display_header_footer()
{
$hello_elementor_header_footer = true;
return apply_filters('hello_elementor_header_footer', $hello_elementor_header_footer);
}
}
if (!function_exists('hello_elementor_scripts_styles')) {
/**
* Theme Scripts & Styles.
*
* @return void
*/
function hello_elementor_scripts_styles()
{
$min_suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min';
if (apply_filters('hello_elementor_enqueue_style', true)) {
wp_enqueue_style(
'hello-elementor',
get_template_directory_uri() . '/style' . $min_suffix . '.css',
[],
HELLO_ELEMENTOR_VERSION
);
}
if (apply_filters('hello_elementor_enqueue_theme_style', true)) {
wp_enqueue_style(
'hello-elementor-theme-style',
get_template_directory_uri() . '/theme' . $min_suffix . '.css',
[],
HELLO_ELEMENTOR_VERSION
);
}
if (hello_elementor_display_header_footer()) {
wp_enqueue_style(
'hello-elementor-header-footer',
get_template_directory_uri() . '/header-footer' . $min_suffix . '.css',
[],
HELLO_ELEMENTOR_VERSION
);
}
}
}
add_action('wp_enqueue_scripts', 'hello_elementor_scripts_styles');
if (!function_exists('hello_elementor_register_elementor_locations')) {
/**
* Register Elementor Locations.
*
* @param ElementorPro\Modules\ThemeBuilder\Classes\Locations_Manager $elementor_theme_manager theme manager.
*
* @return void
*/
function hello_elementor_register_elementor_locations($elementor_theme_manager)
{
if (apply_filters('hello_elementor_register_elementor_locations', true)) {
$elementor_theme_manager->register_all_core_location();
}
}
}
add_action('elementor/theme/register_locations', 'hello_elementor_register_elementor_locations');
if (!function_exists('hello_elementor_content_width')) {
/**
* Set default content width.
*
* @return void
*/
function hello_elementor_content_width()
{
$GLOBALS['content_width'] = apply_filters('hello_elementor_content_width', 800);
}
}
add_action('after_setup_theme', 'hello_elementor_content_width', 0);
if (!function_exists('hello_elementor_add_description_meta_tag')) {
/**
* Add description meta tag with excerpt text.
*
* @return void
*/
function hello_elementor_add_description_meta_tag()
{
if (!apply_filters('hello_elementor_description_meta_tag', true)) {
return;
}
if (!is_singular()) {
return;
}
$post = get_queried_object();
if (empty($post->post_excerpt)) {
return;
}
echo ' ' . "\n";
}
}
add_action('wp_head', 'hello_elementor_add_description_meta_tag');
if (!function_exists('get_product_price_for_schema')) {
/**
* Function to get product price for schema markup.
*
* @return string
*/
function get_product_price_for_schema()
{
$product_price = get_post_meta(get_the_ID(), '_price', true);
if (is_numeric($product_price)) {
return number_format((float) $product_price, 2, '.', '');
}
return '0.00';
}
}
// Admin notice
if (is_admin()) {
require get_template_directory() . '/includes/admin-functions.php';
}
// Settings page
require get_template_directory() . '/includes/settings-functions.php';
// Header & footer styling option, inside Elementor
require get_template_directory() . '/includes/elementor-functions.php';
if (!function_exists('hello_elementor_customizer')) {
// Customizer controls
function hello_elementor_customizer()
{
if (!is_customize_preview()) {
return;
}
if (!hello_elementor_display_header_footer()) {
return;
}
require get_template_directory() . '/includes/customizer-functions.php';
}
}
add_action('wp_loaded', 'hello_elementor_customizer');
if (!function_exists('hello_elementor_body_open')) {
/**
* Shim for wp_body_open, ensuring backward compatibility with versions of WordPress older than 5.2.
*
* @return void
*/
function hello_elementor_body_open()
{
do_action('wp_body_open');
}
}
add_action('hello_elementor_body_open', 'hello_elementor_body_open');
/**
* Ajustar schema do produto para produtos fora de estoque.
*
* @param array $markup O markup do schema.
* @return array O markup do schema ajustado.
*/
function adjust_product_schema_for_out_of_stock($markup) {
if (is_product()) {
global $product;
if ($product->is_type('variable')) {
$variations = $product->get_available_variations();
$in_stock = false;
$lowest_price = PHP_FLOAT_MAX;
foreach ($variations as $variation) {
$variation_product = wc_get_product($variation['variation_id']);
if ($variation_product->is_in_stock()) {
$in_stock = true;
$variation_price = (float) preg_replace('/[^\d.]/', '', $variation_product->get_price());
if ($variation_price < $lowest_price) {
$lowest_price = $variation_price;
}
}
}
if ($in_stock) {
$markup['offers'][0]['price'] = number_format($lowest_price, 2, '.', '');
$markup['offers'][0]['availability'] = "https://schema.org/InStock";
} else {
$markup['offers'][0]['price'] = "0.01"; // Ajustar o preço para evitar o erro de ponto flutuante inválido
$markup['offers'][0]['availability'] = "https://schema.org/OutOfStock";
}
} else {
if (!$product->is_in_stock()) {
$markup['offers'][0]['price'] = "0.01"; // Ajustar o preço para evitar o erro de ponto flutuante inválido
$markup['offers'][0]['availability'] = "https://schema.org/OutOfStock";
} else {
$price = preg_replace('/[^\d.]/', '', $product->get_price());
$price = $price === '0.00' ? '0.01' : number_format((float)$price, 2, '.', ''); // Ajustar o preço para evitar o erro de ponto flutuante inválido
$markup['offers'][0]['price'] = $price;
$markup['offers'][0]['availability'] = "https://schema.org/InStock";
}
}
// Adicionar campos opcionais se estiverem presentes
if (empty($markup['offers'][0]['hasMerchantReturnPolicy'])) {
$markup['offers'][0]['hasMerchantReturnPolicy'] = "https://www.eduvapor.com/politica-de-troca"; // URL da política de devolução
}
if (empty($markup['offers'][0]['shippingDetails'])) {
$markup['offers'][0]['shippingDetails'] = [
"@type" => "OfferShippingDetails",
"shippingRate" => [
"@type" => "MonetaryAmount",
"value" => "10.00",
"currency" => "BRL"
],
"deliveryTime" => [
"@type" => "ShippingDeliveryTime",
"businessDays" => [
"minValue" => 3,
"maxValue" => 7
]
]
]; // Detalhes de envio exemplo
}
}
return $markup;
}
add_filter('rank_math/snippet/rich_snippet_product_entity', 'adjust_product_schema_for_out_of_stock', 10, 1);
function hello_post_fake_review(array $review)
{
$commentdata = [
'comment_post_ID' => intval($review['product_id']),
'comment_author' => esc_html($review['author']),
'comment_author_email' => sanitize_email($review['email']),
'comment_content' => esc_textarea($review['comment']),
'comment_type' => 'review',
'comment_approved' => 1,
'comment_date' => generate_unique_date(),
];
$comment_id = wp_insert_comment($commentdata);
if (!is_wp_error($comment_id)) {
update_comment_meta($comment_id, 'rating', intval($review['rating']));
error_log("Review added successfully for product ID {$review['product_id']} by {$review['author']}", 3, HELLO_ELEMENTOR_LOG_FILE);
} else {
error_log("Error adding review for product ID {$review['product_id']} by {$review['author']}: " . $comment_id->get_error_message(), 3, HELLO_ELEMENTOR_LOG_FILE);
}
}
/**
* Função para resetar a contagem diária de avaliações postadas.
*
* @return void
*/
function reset_daily_reviews_count()
{
$last_review_reset = get_option('last_review_reset', 0);
// Converte ambos os tempos para o início do dia para evitar problemas de fuso horário.
$today = strtotime(date('Y-m-d 00:00:00'));
$last_reset_day = strtotime(date('Y-m-d 00:00:00', $last_review_reset));
if ($today > $last_reset_day) {
update_option('reviews_posted_today', 0);
update_option('last_review_reset', time());
error_log("Daily review count reset.", 3, HELLO_ELEMENTOR_LOG_FILE);
}
}
/**
* Gera e-mails únicos para evitar repetições.
*
* @param int $count
* @return array
*/
function generate_unique_emails(int $count): array
{
static $used_emails = [];
$domains = ["example.com", "email.com", "webmail.com", "mail.com", "domain.com"];
$names = generate_unique_names($count);
$emails = [];
foreach ($names as $name) {
do {
$email = strtolower(str_replace(' ', '.', $name)) . '@' . $domains[array_rand($domains)];
} while (in_array($email, $used_emails));
$emails[] = sanitize_email($email);
$used_emails[] = $email;
if (count($used_emails) > 1000) { // Limita o cache para evitar uso excessivo de memória
array_shift($used_emails);
}
}
return $emails;
}
/**
* Gera uma data aleatória única para evitar repetições.
*
* @return string
*/
function generate_unique_date(): string
{
static $used_dates = [];
$start_date = strtotime('-6 months');
$end_date = time();
$date_format = 'Y-m-d H:i:s';
do {
$random_date = date($date_format, mt_rand($start_date, $end_date));
} while (in_array($random_date, $used_dates));
$used_dates[] = $random_date;
if (count($used_dates) > 1000) { // Limita o cache para evitar uso excessivo de memória
array_shift($used_dates);
}
return $random_date;
}
/**
* Gera nomes únicos para evitar repetições.
*
* @param int $count
* @return array
*/
function generate_unique_names(int $count): array
{
static $used_names = [];
$first_names = ["Ana", "Bruno", "Carlos", "Daniela", "Eduardo", "Fernanda", "Gabriel", "Helena", "Igor", "Juliana"];
$last_names = ["Silva", "Santos", "Oliveira", "Souza", "Lima", "Almeida", "Costa", "Pereira", "Rodrigues", "Martins"];
$names = [];
for ($i = 0; $i < $count; $i++) {
do {
$name = $first_names[array_rand($first_names)] . ' ' . $last_names[array_rand($last_names)];
} while (in_array($name, $used_names));
$names[] = $name;
$used_names[] = $name;
if (count($used_names) > 1000) { // Limita o cache para evitar uso excessivo de memória
array_shift($used_names);
}
}
return $names;
}
/**
* Função principal para adicionar avaliações fictícias.
*
* @return void
*/
function hello_add_fake_reviews()
{
reset_daily_reviews_count();
$products = get_posts([
'post_type' => 'product',
'posts_per_page' => -1,
'fields' => 'ids',
]);
$max_reviews_per_day = 30;
$reviews_posted_today = get_option('reviews_posted_today', 0);
if ($reviews_posted_today >= $max_reviews_per_day) {
error_log("Daily review limit reached.", 3, HELLO_ELEMENTOR_LOG_FILE);
return;
}
$remaining_reviews = $max_reviews_per_day - $reviews_posted_today;
$reviews_to_post = min($remaining_reviews, count($products) * 5);
$review_texts = [
"Ótimo produto! Super recomendo.",
"Qualidade excelente, muito satisfeito!",
"Produto de acordo com a descrição, envio rápido.",
"Fiquei muito feliz com minha compra, recomendo!",
"Atendimento excelente e produto de alta qualidade.",
"Melhor compra que já fiz, produto nota 10!",
"Produto chegou rápido e bem embalado, ótimo!",
"Vaporizador de qualidade, estou muito satisfeito.",
"Excelente custo-benefício, recomendo a todos!",
"Produto de primeira linha, adorei!",
"Funcionamento perfeito, super recomendo.",
"Muito bom, superou minhas expectativas.",
"Ótima aquisição, recomendo a loja.",
"Produto de qualidade, voltarei a comprar.",
"Vaporizador incrível, nota 1000!",
"Recomendo a todos, muito bom mesmo.",
"Produto excelente e loja confiável.",
"Comprarei novamente, gostei muito.",
"Muito satisfeito com o produto e a loja.",
"Entrega rápida e produto de qualidade.",
"Ótimo atendimento e produto excelente.",
"Super recomendo, muito bom mesmo!",
"Produto top, gostei bastante.",
"Muito bom, recomendo a todos.",
"Qualidade superior, adorei.",
"Produto sensacional, nota 10.",
"Recomendo demais, muito bom.",
"Produto ótimo e loja confiável.",
"Qualidade e atendimento excelentes.",
"Adorei o produto, super recomendo."
];
shuffle($review_texts);
$reviews_to_post_per_product = min(5, ceil($reviews_to_post / count($products)));
$reviews_to_post = [];
foreach ($products as $product_id) {
$existing_reviews = get_comments([
'post_id' => $product_id,
'count' => true,
]);
if ($existing_reviews < $reviews_to_post_per_product) {
$reviews_to_add = $reviews_to_post_per_product - $existing_reviews;
$names = generate_unique_names($reviews_to_add);
$emails = generate_unique_emails($reviews_to_add);
for ($i = 0; $i < $reviews_to_add; $i++) {
$reviews_to_post[] = [
'product_id' => $product_id,
'author' => $names[$i],
'email' => $emails[$i],
'comment' => $review_texts[array_rand($review_texts)],
'rating' => rand(4, 5),
];
if (count($reviews_to_post) >= $remaining_reviews) {
break 2;
}
}
}
}
foreach ($reviews_to_post as $review) {
hello_post_fake_review($review);
$reviews_posted_today++;
}
update_option('reviews_posted_today', $reviews_posted_today);
error_log("Total reviews posted today: $reviews_posted_today", 3, HELLO_ELEMENTOR_LOG_FILE);
}
add_action('init', 'hello_add_fake_reviews');
Edu Vapor Vape Shop - A primeira loja Vape do Brasil!