rob.m rob.m - 1 month ago 11
jQuery Question

Loop in php the posts and add a class to polygon (leaflet)

I am using Wordpress, I am looping my articles and for each article I am creating a case and adding a class. The case name and the class name are taken from custom fields attached to each post.

However what happens is that if I have 2 articles related to a country e.g. Australia, the loop will say "found an article for Australia with this class, set a case and add its class". However, if i have 2 articles related to Australia, the case is already created for it therefore I won't be able to add a second class as it will skip it. Therefore I think I am doing it wrong and I shouldn't use

switch case
.

The idea is to check for matches between the
country custom field
and the
sovereignt property within the geoson
, so that I can draw the country polygons if any article is related to a country, yet if I have 2 articles related to one country, the polygon is only drew once but there is the class issue as per above.

geojson = L.geoJson(statesData, {
style: style,
style: function(feature) {
<?php
query_posts(array(
'post_type' => 'post',
'showposts' => -1
));
?>
switch (feature.properties.sovereignt) {
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
case '<?php the_field("country"); ?>': return {className: '_<?php the_field("year"); ?>'};
<?php endwhile; endif;?>
}
},
onEachFeature: onEachFeature
}).addTo(map);


The switch case example i got it from leaflet docs

Answer

What you're doing wrong is mixing PHP and JavaScript every two lines. This is a Recipe For Disasterâ„¢, as you've got to think about the execution of two different intertwined languages. While that looks like it works, it gets messy fast.

Instead, separate the logic a bit, and take control over the variables around:

<?php // Preprocess some data ?>

var something = <?php echo JSON_encode(some_clearly_defined_data); ?>

do_something_with_the_data();

i.e.:

<?php
classesForCountries = [];
while (have_posts()) {
    classesForCountries[ post.country ] += post.className + ' ';
}
?>

// Now this should look something like {"Australia": "2006 2010 "}
var classNameMap = <?php echo JSON_encode(classesForCountries); ?>;

geojson = L.geoJson(statesData, {
    style: function(feature) {
        // Now the logic is a simple hashmap look-up
        var classes = classNameMap[feature.properties.sovereignt];
        if (classes) {
            return {className: classes};
        }
    },
}).addTo(map);

Doesn't that look cleaner? While you're able to mix PHP and JS together, you should keep your code human-readable and easy to understand. Create variables and states you can inspect. Make code that your future self will want to read.