0

I have meta_key 'oyuncular' and it has meta values with line breaks. I want to get them and display in table with two column. Name and Role Name

enter image description here

$names = get_post_meta( get_the_ID(), 'oyuncular', true );
$namesArray = explode( '\n', $names);

<div class="table-responsive">
    <table class="table table-bordered">
        <thead>
        <tr class="table-success">
            <th>#</th>
            <th>Name</th>
            <th>Role Name</th>
        </tr>
        </thead>
        <tbody>

        <?php

        foreach( $namesArray as $key => $name ) { ?>

            <tr>
                <th scope="row">1</th>
                <td>Name</td>
                <td>Role Name</td>
            </tr>

            <?php
        }

        ?>
        </tbody>
    </table>
</div>
3

You can use explode() or preg_split(), like this:

$i = 0;
foreach( $namesArray as $key => $name ) {
    $arr = explode( ' -', $name, 2 );
    //$arr = preg_split( '/\s+\-/', $name, 2 );

    $name2 = isset( $arr[0] ) ? trim( $arr[0] ) : '';
    $role_name = isset( $arr[1] ) ? trim( $arr[1] ) : '';

    if ( $name2 || $role_name ) : $i++; ?>

    <tr>
        <th scope="row"><?php echo $i; ?></th>
        <td><?php echo $name2; ?></td>
        <td><?php echo $role_name; ?></td>
    </tr>

    <?php endif;
}

Also, you need to wrap the \n in double-quotes:

$namesArray = explode( "\n", $names); // not '\n'

Otherwise, the \n will not be evaluated as "new line".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.