// shortcode for parsha info - from chat gpt be careful
// Function to fetch the weekly Parsha from the Hebcal API
function getWeeklyParsha() {
$url = 'https://www.hebcal.com/shabbat?cfg=json';
$response = file_get_contents($url);
if ($response === false) {
return 'Error: Unable to fetch data from the API.';
}
$data = json_decode($response, true);
if (!$data || !isset($data['items']) || empty($data['items'])) {
return 'Error: Invalid data received from the API.';
}
$weeklyParsha = array();
foreach ($data['items'] as $item) {
if (isset($item['category']) && stripos($item['category'], 'parashat') !== false) {
$parshaTitle = $item['title'];
$parshaTitle = preg_replace('/^Parashat /', '', $parshaTitle); // Remove "Parashat " from beginning
$weeklyParsha['hebrew'] = $item['hebrew'];
$weeklyParsha['english'] = $parshaTitle;
break;
}
}
if (empty($weeklyParsha)) {
return 'Error: Parsha for the category not found.';
}
return $weeklyParsha;
}
function getCategoryLinkByParsha($parshaData) {
// If API returned nothing or invalid data
if (!is_array($parshaData) || !isset($parshaData['english'])) {
return home_url(); // Fallback to homepage
}
$slug = sanitize_title_with_dashes($parshaData['english']); // Convert English name to slug format
$args = array(
'taxonomy' => 'category',
'slug' => $slug,
'fields' => 'all',
);
$categories = get_terms($args);
// Check if categories exists and has results
if (is_wp_error($categories) || empty($categories)) {
return home_url(); // Fallback to homepage
}
$categoryLink = get_term_link($categories[0]);
// One last check in case get_term_link fails
if (is_wp_error($categoryLink)) {
return home_url();
}
return $categoryLink;
}
function parsha_link_shortcode() {
$weeklyParsha = getWeeklyParsha();
// Check if API returned valid data
if (!is_array($weeklyParsha) || empty($weeklyParsha)) {
return ''; // Return empty string instead of breaking the page
}
// Make sure the required keys exist
if (!isset($weeklyParsha['hebrew']) || !isset($weeklyParsha['english'])) {
return ''; // Return empty string if keys are missing
}
$categoryLink = getCategoryLinkByParsha($weeklyParsha);
$output = '' . esc_html($weeklyParsha['hebrew']) . '';
return $output;
}
add_shortcode('parsha_link', 'parsha_link_shortcode');
// Function to fetch holidays from the Hebcal API
function getHolidays($type = 'major', $count = 1, $days = 45) {
// Set up the API URL based on holiday type
$url = 'https://www.hebcal.com/hebcal/?v=1&cfg=json&nx=10';
// Add holiday type parameter
if ($type === 'major') {
$url .= '&maj=on';
} elseif ($type === 'minor') {
$url .= '&min=on';
} elseif ($type === 'all') {
$url .= '&maj=on&min=on';
}
$response = file_get_contents($url);
if ($response === false) {
return 'Error: Unable to fetch data from the API.';
}
$data = json_decode($response, true);
if (!$data || !isset($data['items']) || empty($data['items'])) {
return 'Error: Invalid data received from the API.';
}
$currentTimestamp = strtotime('today');
$maxTimestamp = strtotime('+' . $days . ' days');
$holidays = [];
foreach ($data['items'] as $item) {
// Skip evening before holidays
if (isset($item['title']) && stripos($item['title'], 'Erev') !== false) {
continue;
}
// Make sure we filter by the correct category based on type
if ($type === 'major' && (!isset($item['subcat']) || $item['subcat'] !== 'major')) {
continue;
} elseif ($type === 'minor' && (!isset($item['subcat']) || $item['subcat'] !== 'minor')) {
continue;
}
if (isset($item['date']) && isset($item['hebrew']) && isset($item['title'])) {
$holidayTimestamp = strtotime($item['date']);
if ($holidayTimestamp >= $currentTimestamp && $holidayTimestamp <= $maxTimestamp) {
// Get basic holiday name from the title field
$baseTitle = preg_replace('/ [IVX]+$/', '', $item['title']); // Remove Roman numerals
// Store original for debugging
$originalHebrew = $item['hebrew'];
// Clean Hebrew name with our direct approach
$hebrewName = stripHebrewDayIndicator($originalHebrew);
// Avoid duplicates (same holiday on different days)
$key = $baseTitle; // Use English name as key
if (!isset($holidays[$key])) {
$holidays[$key] = array(
'hebrew' => $hebrewName,
'english' => $baseTitle,
'date' => $item['date'],
'timestamp' => $holidayTimestamp,
'category' => isset($item['subcat']) ? $item['subcat'] : 'unknown',
'original_hebrew' => $originalHebrew
);
}
// If we have enough holidays, break
if (count($holidays) >= $count) {
break;
}
}
}
}
// Sort holidays by timestamp (closest first)
uasort($holidays, function($a, $b) {
return $a['timestamp'] - $b['timestamp'];
});
return array_values($holidays); // Return indexed array instead of associative
}
// New direct approach to strip Hebrew day indicators
function stripHebrewDayIndicator($string) {
// Create an explicit mapping of Hebrew day indicators to remove
$dayIndicators = [
' א', ' א׳', ' ב', ' ב׳', ' ג', ' ג׳', ' ד', ' ד׳',
' ה', ' ה׳', ' ו', ' ו׳', ' ז', ' ז׳', ' ח', ' ח׳',
' ט', ' ט׳', ' י', ' י׳',
" א'", " ב'", " ג'", " ד'", " ה'", " ו'", " ז'", " ח'", " ט'", " י'"
];
// Check if the string ends with any of these day indicators
foreach ($dayIndicators as $indicator) {
if (mb_substr($string, -mb_strlen($indicator, 'UTF-8'), null, 'UTF-8') === $indicator) {
return mb_substr($string, 0, mb_strlen($string, 'UTF-8') - mb_strlen($indicator, 'UTF-8'), 'UTF-8');
}
}
return $string;
}
// Function to find the holiday category under the "moadim" parent
function findHolidayCategoryUnderMoadim($hebrewName, $englishName) {
// Always clean the Hebrew name again to be sure
$hebrewName = stripHebrewDayIndicator($hebrewName);
// First find the moadim parent category
$moadim_cat = get_term_by('slug', 'moadim', 'category');
if (!$moadim_cat) {
return ''; // Parent category not found
}
// Get all child categories of moadim
$holiday_cats = get_categories(array(
'hide_empty' => false,
'parent' => $moadim_cat->term_id,
'hierarchical' => true,
));
// Prepare holiday names for comparison
$hebrew_slug = sanitize_title($hebrewName);
$english_slug = sanitize_title($englishName);
// First try exact Hebrew name match
foreach ($holiday_cats as $cat) {
if ($cat->name === $hebrewName) {
return get_category_link($cat->term_id);
}
}
// Then try exact English name match
foreach ($holiday_cats as $cat) {
if (strcasecmp($cat->name, $englishName) === 0) {
return get_category_link($cat->term_id);
}
}
// Try slug matching
foreach ($holiday_cats as $cat) {
if ($cat->slug === $hebrew_slug || $cat->slug === $english_slug) {
return get_category_link($cat->term_id);
}
}
// Try to find if it's a sub-sub-category
foreach ($holiday_cats as $parent_cat) {
$sub_cats = get_categories(array(
'hide_empty' => false,
'parent' => $parent_cat->term_id,
));
foreach ($sub_cats as $sub_cat) {
// Check exact name matches
if ($sub_cat->name === $hebrewName || strcasecmp($sub_cat->name, $englishName) === 0) {
return get_category_link($sub_cat->term_id);
}
// Check slug matches
if ($sub_cat->slug === $hebrew_slug || $sub_cat->slug === $english_slug) {
return get_category_link($sub_cat->term_id);
}
}
}
// No match found
return '';
}
// Shortcode function to return holiday(s) as link(s) to the corresponding category
function holiday_link_shortcode($atts) {
// Parse attributes
$atts = shortcode_atts(array(
'type' => 'major', // Options: major, minor, all
'count' => 1, // Number of holidays to retrieve
'separator' => '
', // Default to line break for multiple holidays
'debug' => 'false', // Add debug info
), $atts, 'holiday_link');
// Validate parameters
$type = in_array($atts['type'], array('major', 'minor', 'all')) ? $atts['type'] : 'major';
$count = max(1, intval($atts['count']));
$separator = $atts['separator'];
$debug = ($atts['debug'] === 'true');
// Get holidays from the API
$holidays = getHolidays($type, $count);
if (is_string($holidays) && strpos($holidays, 'Error:') === 0) {
return $holidays; // Return error message
}
if (empty($holidays)) {
return 'No upcoming holidays found.';
}
$output_parts = array();
foreach ($holidays as $holiday) {
// Use the already cleaned Hebrew name from getHolidays
// But clean it again as a safeguard
$hebrewName = stripHebrewDayIndicator($holiday['hebrew']);
$englishName = $holiday['english'];
// Add debug info if requested
if ($debug) {
$debug_info = " [OH: " . $holiday['original_hebrew'] .
", F: " . $hebrewName .
", E: " . $englishName . "]";
} else {
$debug_info = "";
}
// Try to find the holiday category under "moadim"
$categoryLink = findHolidayCategoryUnderMoadim($hebrewName, $englishName);
// Build the holiday link or text
if ($categoryLink) {
$output_parts[] = '' . esc_html($hebrewName) . '' . $debug_info;
} else {
$output_parts[] = esc_html($hebrewName) . $debug_info;
}
}
// Join all holiday parts with the separator
return implode($separator, $output_parts);
}
add_shortcode('holiday_link', 'holiday_link_shortcode');
// Test function to verify the day indicator removal works
// Add this to a test page or admin area
function test_hebrew_cleaning() {
$tests = [
'שבועות א' => 'שבועות',
'שבועות א׳' => 'שבועות',
'שבועות ב' => 'שבועות',
'שבועות ב׳' => 'שבועות',
'חנוכה: נר ב׳' => 'חנוכה: נר',
'טו בשבט' => 'טו בשבט' // Should remain unchanged
];
$results = [];
foreach ($tests as $input => $expected) {
$actual = stripHebrewDayIndicator($input);
$results[] = [
'input' => $input,
'expected' => $expected,
'actual' => $actual,
'success' => ($actual === $expected)
];
}
// Output results
$output = '
Input | Expected | Actual | Success |
---|---|---|---|
' . esc_html($result['input']) . ' | ' . esc_html($result['expected']) . ' | ' . esc_html($result['actual']) . ' | ' . ($result['success'] ? '✓' : '✗') . ' |