Daniels Ans
Daniels Ans

Reputation: 11

PHP add attribute to objects in foreach loop

So my problem is - I've div with this kind of structure:

<div>
<strong> Value 1</strong>
<strong> Value 2</strong>
<strong> Value 3</strong>
</div>

It's a wordpress site, I've posts with slugs like - /value-1/ /value-2/ etc. I need to use this wp function - wp_some_function(get_ID_by_slug('any-page')); and add attribute to each of those strong tags with that post id. So it would look like:

<div>
<strong id="2334"> Value 1</strong>
<strong id="34322"> Value 2</strong>
<strong id="2323"> Value 3</strong>
</div>

So basically I need to get content of each , replace spaces with dash, and add it in function I wrote above to get page ID, which I need to add as "id" attribute".

Upvotes: 1

Views: 454

Answers (1)

Ravinder Kumar
Ravinder Kumar

Reputation: 399

Try this or drive your code from it

<?php
    function ravs_postID($my_slug)
      $slug_to_get = str_replace(' ','-',$my_slug);
      $args=array(
       'name' => $slug_to_get,
       'post_type' => 'post',
       'post_status' => 'publish',
       'showposts' => 1,
       'caller_get_posts'=> 1
     );
     $my_posts = get_posts($args);
     if( $my_posts ) {
      return $my_posts[0]->ID;
     }
    }
    ?>
    <div>
     <strong id="<?php echo ravs_postID('Value 1'); ?>"> Value 1</strong>
     <strong id="<?php echo ravs_postID('Value 2'); ?>"> Value 2</strong>
     <strong id="<?php echo ravs_postID('Value 3'); ?>"> Value 3</strong>
    </div>

Upvotes: 1

Related Questions