1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] Select multiple meta values with $wpdb->get_result

Discussão em 'Outras Linguagens' iniciado por Stack, Outubro 9, 2024 às 22:32.

  1. Stack

    Stack Membro Participativo

    I'm trying to put together a google map for wordpress posts, which have a lat and long saved as meta values.

    I need the lat and long output as two separate values in a list such that I could call them with result[1] and result[2]. Right now I can output both lat and long but they're as separate entries on a list ( i.e. each post title will be listed twice, once for lat and once for long, I need it to be listed once with lat and long as two of it's values)

    Here's how the code's looking now (the printf is just to test the output of $result):

    <?php
    $lat = 'latitude';
    $long = 'longitude';
    $results = $wpdb->get_results( "
    SELECT
    post_title,
    meta_value
    FROM {$wpdb->posts}
    INNER JOIN {$wpdb->postmeta}
    ON ( $wpdb->posts.ID = {$wpdb->postmeta}.post_id )
    WHERE meta_key = '$lat'
    OR meta_key = '$long'
    " );

    foreach( $results as $result )
    {
    printf( '<pre>%s</pre>', htmlspecialchars( var_export( $result, true ) ) );
    }

    ?>

    <style type="text/css">
    html, body { height: 100%; margin: 0; padding: 0; }
    #map { height: 350px; width:100%; }
    </style>

    <script type="text/javascript">



    // MAP

    function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: {lat: 53.343156, lng: -6.258545},
    scrollwheel: false
    });

    setMarkers(map);
    }

    // LOCATIONS

    var locations = [
    <?php

    foreach( $results as $result ) {

    echo "\t\t\t['"
    . str_replace("'", "\'", $result[0])
    . "', " . $result[1]
    . ", '" . $result[3] . "'"
    . "],\n";
    } ?> ];


    function setMarkers(map) {
    // Adds markers to the map.

    for (var i = 0; i < results.length; i++) {
    var result = results;
    var marker = new google.maps.Marker({
    position: {lat: result[1], lng: result[2]},
    map: map,
    title: result[0]
    });
    }
    }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=MyMapKey&callback=initMap">
    </script>

    Continue reading...

Compartilhe esta Página