簡體   English   中英

獲取xml屬性

[英]Get xml attribute

我正在使用一個具有多個小部件的插件,每個小部件填充一個不同的XML文件。 我的XML文件代表我所有的類別(我有7個類別),並且其中包含多個項目。

XML范例:

<channel>
  <category> This XML category </category>
  <item>
    <title> Item title 1 </title>
    <description> This is the first item description. </description>
  </item>  
  <item>
    <title> Item title 2 </title>
    <description> This is the second item description. </description>
  </item>    
</channel>

我的插件要做的是獲取一個XML文件,並用它來填充其項目的小部件。 每個項目都有一個按鈕鏈接到它,當我單擊它時,它將調用jQuery函數。

PHP的:

foreach ( $channel->channel->item as $item )  {
  echo "<div class='xppArticle'>";
    echo "<h2>" . $item->title . "</h2>";
    if ( preg_match( '/p$/', $this->set_paragraph_length_display( $item->description, 400 ) ) || preg_match( '/\\/$/', $this->set_paragraph_length_display( $item->description, 400 ) ) ) {
      echo "<p>". html_entity_decode( $this->set_paragraph_length_display( $item->description, 375 ) ) . "(...)" ."</p>";
    }
    else {
      echo "<p>". html_entity_decode( $this->set_paragraph_length_display( $item->description, 400 ) ) . "(...)" . "</p>";
    }

    global $wpdb;
    $query = $wpdb->prepare ( 'SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title = %s', $item->title );
    $cID = $wpdb->get_var( $query ) ;

    if ( ! empty( $cID ) ) {
      echo "<input type='button' class='putPending button-primary' value='Already publish' disabled='disabled' />";
    }
    else {
      echo "<input type='button' class='putPending button-primary' value='Edit' />";
    }
    echo "<hr />";
  echo "</div>";
}

jQuery的:

jQuery( '.putPending' ).live( 'click', function( ) {
  var title = jQuery( this ).siblings( "h2" ).text( ); 

  jQuery.ajax( {
    url: ajaxurl,
    datatype: 'json',
    method: 'POST',
    data:
    {
      action: 'ajax_fill_post',
      title: title,
    },
    success: function( data )
    {
      var result = JSON.parse( data );
      window.location.href = result.url;
    }            
  });        
}); 

我的jQuery將標題返回給我的post_item_function (我不會顯示它,因為它超過100行)。 foreach獲取$ current_category並搜索與$ title對應的項目標題。 沒有$ current_category,我無法在單個foreach中做到這一點,它將為我的插件增加250-300多行。

在構建的循環之外,您可以簡單地迭代category XML標記,然后為其創建隱藏的輸入。

foreach ( $channel->channel->category as $idx => $category);
    echo '<input type="hidden" name="category" class="category" data-categoryIndex="'.$idx.'"  value="'.$category.'"/>';
endforeach;

然后,您可以這樣訪問它:

$('.category[data-categoryIndex="'+1/2/3/etc+'"]').val();

這將為您提供基於data-categoryIndex="1/2/3/etc" $idx data-categoryIndex="1/2/3/etc"的類別,該data-categoryIndex="1/2/3/etc"已由我們的$idx變量在我們的foreach循環中分配。

如果您只有一個類別,那么很簡單:

$('.category').val();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM