GabouhSk8
GabouhSk8

Reputation: 169

split a string php and save it in variable

Hi all and thanks in advance. I have this code where I get the images attached to a post parent, and I want to display them in a slider with arrows left and right. The thing is that when I echo $imagenes, my code gives me 3 URLs in a string, and I need to split the string so I can have an independent string and then be able to assign it to a javascript and make it work.

I already use explode, split and str_split and I couldn't get it. I just want to have every URL in a variable to make an action when it is clicked. Any help would be very appreciated.

Here is my code:

<?php
        require_once("../../../../../wp-load.php");

        $id = $_GET['id'];

        $args = array('p' => $id, 'post_type' => 'myportfoliotype');

        $query = new WP_Query($args);

        if ( $query->have_posts() ) {
            while ( $query->have_posts() ) {
                $query->the_post();
                $texto = get_the_content();
                $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'any', 'post_parent' => $post->ID ); 
                $attachments = get_posts($args);

                if ($attachments) {
                    foreach ( $attachments as $attachment ) {
                        //echo $attachment->ID."<br>";
                        $imagenes = wp_get_attachment_image_src($attachment->ID,'fullsize',false,'');
                        $imagenes = $imagenes[0];

                    }
                }
            }
        }
        wp_reset_postdata();

        ?>

Upvotes: 0

Views: 560

Answers (1)

Expedito
Expedito

Reputation: 7795

Change this:

if ($attachments) {
    foreach ( $attachments as $attachment ) {
        //echo $attachment->ID."<br>";
        $imagenes = wp_get_attachment_image_src($attachment->ID,'fullsize',false,'');
        $imagenes = $imagenes[0];
    }
}

To:

if ($attachments) {
    $imgs = array();
    foreach ( $attachments as $attachment ) {
        //echo $attachment->ID."<br>";
        $imagenes = wp_get_attachment_image_src($attachment->ID,'fullsize',false,'');
        $imgs[] = $imagenes[0];
    }
}

Now each value of $imagenes[0] is stored in its own array key:

print_r($imgs);

Upvotes: 1

Related Questions