2016-11-03 100 views
0

我使用Wordpress,我正在循環我的文章和每篇文章我創建一個案例並添加一個類。案例名稱和類名取自每個帖子附加的自定義字段。在php中循環帖子並添加一個類到多邊形(小冊子)

但是,如果我有兩篇與某個國家相關的文章,例如澳大利亞,該循環會說「爲這個班級找到一篇澳大利亞文章,設置一個案例並添加其課程」。但是,如果我有兩篇與澳大利亞有關的文章,則已經爲此創建了案例,因此我將無法添加第二個課程,因爲它會跳過它。所以我認爲我做錯了,我不應該使用switch case

的想法是,以檢查country custom fieldsovereignt property within the geoson之間的匹配,這樣我就可以得出該國的多邊形,如果任何物品,關係到一個國家,但如果我有2頁涉及到一個國家的文章,多邊形只畫了一次,但有上面的類問題。

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); 

開關案例我是從leaflet docs

回答

0

你做錯了什麼是混合PHP和JavaScript每兩行。這是一個Recipe For Disaster™,你必須考慮執行兩種不同的交織語言。雖然這看起來像它的工作,它很快凌亂

相反,獨立的邏輯一點,並採取控制變量周圍:

<?php // Preprocess some data ?> 

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

do_something_with_the_data(); 

即:

<?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); 

不看起來更清潔?雖然您可以將PHP和JS混合在一起,但您應該保持代碼易於理解,並且易於理解。創建您可以檢查的變量和狀態。製作你未來的自己想要閱讀的代碼。

+0

P.S.請原諒我生鏽的PHP,這是一段時間。 – IvanSanchez

+0

post.country是什麼?你的意思是我應該輸出這個字段,比如the_field(「country」); ? –

+0

以任何你需要的方式輸出它。考慮我的PHP是僞代碼。 – IvanSanchez

相關問題