I try to make a calendar for my wordpress site and I have a code that shows fine.
I run into the fact that I want to add a custom field to posts with the same date. All the loops in my current code make it too complex for me.
I’ve already tried a lot and thought I was close to it every now and then, but now I’m stuck.
Can someone help me further?
<?php
$year = date('Y');
$custom_field_key = 'opbrengst'; // Replace with the key of the custom field you want to get the value from
$monthNames = array(
1 => 'Januari',
2 => 'Februari',
3 => 'Maart',
4 => 'April',
5 => 'Mei',
6 => 'Juni',
7 => 'Juli',
8 => 'Augustus',
9 => 'September',
10 => 'Oktober',
11 => 'November',
12 => 'December'
);
for ($month = 1; $month <= 12; $month++) {
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$monthName = $monthNames[$month];
echo "<div class='month'>";
echo "<table class='calendar table-flex'>";
echo "<tr><th colspan='7'>$monthName</th></tr>";
echo "<tr><td>Ma</td><td>Di</td><td>Wo</td><td>Do</td><td>Vr</td><td>Za</td><td>Zo</td></tr>";
for ($i = 1; $i <= $daysInMonth; $i++) {
$dayOfWeek = date('N', strtotime("$year-$month-$i"));
if ($i == 1) {
echo "<tr>";
for ($j = 1; $j < $dayOfWeek; $j++) {
echo "<td></td>";
}
}
$date = "$year-$month-$i";
$args = array(
'date_query' => array(
array(
'year' => $year,
'month' => $month,
'day' => $i,
),
),
'posts_per_page' => -1,
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
$custom_field_value = get_post_meta($post_id, $custom_field_key, true);
// set background color
$custom_field_value > 0 ? $color = "green" : $color = "red";
if ($dayOfWeek == 7) {
echo "<td class="$color">$i<br>$ $custom_field_value</td></tr><tr>";
} else {
echo "<td class="$color">$i<br>$ $custom_field_value</td>";
}
}
} else {
if ($dayOfWeek == 7) {
echo "<td>$i</td></tr><tr>";
} else {
echo "<td>$i</td>";
}
}
}
echo "</tr></table>";
echo "</div>";
}
?>
2
Answers
This is a working example as I want it, but I can't put it together in my calendar.
To add a custom field to posts with the same date, you can modify the code to include a check for the custom field value for each post that matches the current date in the loop that retrieves the posts. If the custom field value matches a certain value, you can add the post ID to an array, and then display the custom field value for all posts in the array.
Here’s an example modification to the code:
I hope this helps