Your issue has nothing to do with the foreach
. The problem is this part:
implode( '&', $social_link['query'] )
implode()
only connects the values. There’s nothing in this code that adds the keys or an =
.
If you want to add an array of key/values as a query string to a URL, WordPress provides a function for this called add_query_arg()
, it accepts an array of key values and a URL to add them to.
In your case you’d use it like this:
<a target="_blank" href="https://wordpress.stackexchange.com/questions/295504/<?php echo esc_url( add_query_arg( $social_link["query'], $social_link['base'] ) ); ?>">
<?php echo $social_link['title']; ?>
</a>
Note my use of esc_url
. As the documentation states:
Important: The return value of add_query_arg() is not escaped by default. Output should be late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting (XSS) attacks.
Another thing to consider is that the values in the query string need to be URL encoded. You can do this with the urlencode()
PHP function:
'title' => urlencode( get_the_title() ),
However you’ll need to do this for every value if you do it like that. A way do to this with less code would be to use array_map()
to apply urlencode()
to every value just before putting into add_query_arg()
:
foreach( $social_links as $social_link ) :
$query_args = array_map( 'urlencode', $social_link['query'] );
?>
<li>
<a target="_blank" href="https://wordpress.stackexchange.com/questions/295504/<?php echo esc_url( add_query_arg( $query_args, $social_link["base'] ) ); ?>">
<?php echo $social_link['title']; ?>
</a>
</li>
<?php
endforeach;