• Hi there,
    I’m having a bit of trouble using an array of links in WordPress’ custom fields.

    I am trying to add multiple links under an “Articles Mentioned” section without having to input multiple instances of the “Articles Mentioned” key in the post editor. I would like to be able to input:

    <a href="" title="">Article 1</a>, <a href="" title="">Article 2</a>

    into the Value field on the Edit Post page and have my code loop through that array, treating each comma separated link as a new value.

    The only way I can get it to work now is if I input multiple “Article Mentioned” keys with multiple Values for each one.

    Does anyone have an idea as to how to solve this riddle?

    I pasted my code below:

    <?php if (have_posts()) : ?>
      <?php while (have_posts()) : the_post();
    	$mentioned = get_post_meta($post->ID, 'Articles Mentioned', $single = false)
    
    ?>
    
    <?php // check if there is Further Reading or Articles Mentioned content
    	if($mentioned !== '') : ?>
    
    	<!-- List headings -->
    	<h3>Post Content & Sources</h3>
    	<h5>Articles Mentioned</h5>
    
    	<!-- List the articles mentioned -->
    	<ul>
    
    	<?php
    	 $length = count($mentioned);
    	 for ($i = 0; $i < $length; $i++) {
    	 ?>
    	<li><?php echo $mentioned[$i]; ?></li>
    
    	<? } ?>
    
    	</ul>
    
    	<h5>Further Reading</h5>
    	<!-- List the further reading -->
    	<?php echo $mentioned[0]; ?>
    
    	<?php
    		 else : echo "";
    		 endif; 
    
    	//If there is no further reading or articles mentioned
    
    	endwhile;
    
    	else :
    	?>
    
    	<h5>Sorry, but you are looking for something that isn't here.</h5>
    
    	<?php endif; ?>

Viewing 1 replies (of 1 total)
  • What you’ve got here– <a href="" title="">Article 1</a>, <a href="" title="">Article 2</a>— isn’t an array so you can’t loop through it. Lucky for you though it is very easy to turn it into an array using explode. With your string, this…

    $anchors = explode(',','<a href="" title="">Article 1</a>, <a href="" title="">Article 2</a>');

    … should give you the array you want.

Viewing 1 replies (of 1 total)

The topic ‘Arrays in Custom Fields’ is closed to new replies.