get_permalink to attachment not working - attachment

I have following code:
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => 12,
'post_status' => null
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li><a href="'.get_permalink( $attachment->ID ).'">';
echo wp_get_attachment_image( $attachment->ID, array('100', '100') );
echo '</a></li>';
}
}
?>
The point of this script is to show last added 12 photos (thumbs of it). And this works perfect. But I want to add second funcionality - link to the page where it comes from (usually native gallery embed into post/page)
The problem is that in this case the link is corrupted. It always links to the very first post. What I am doing wrong?

Try get_attachment_link($attachment->ID).
Or the_attachment_link($attachment->ID) to directly print the anchor tag with the URL

Here is the final version:)
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => 12,
'post_status' => null
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$url = get_permalink( $attachment->ID );
echo '<li><a href="'.strstr($url, '/attachment', true).'">';
echo wp_get_attachment_image( $attachment->ID, array('100', '100') );
echo '</a></li>';
}
}
?>
/attachment is the starting point from which we want to remove everything from the url.

Related

Woocommerce custom billing field (also saved, displayed in back-end and on email)

i'm looking for the perfect all in solution. I want to add a custom billing fiels to Woocommerce based on the user ID. Also i want this field to be displayed in the back-end, saved and on the front end on the users profile, and in the mails.
Till now with the code below it only shows the field on the fornt-end
/* Debiteutnummer front-end*/
add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');
function custom_woocommerce_billing_fields($fields) {
$fields['debiteurnummer'] = array(
'label' => __('debiteurnummer'), // Add custom field label
'placeholder' => _x('Debiteurnummer', 'placeholder', 'woocommerce'), // Add custom field placeholder
'required' => true, // if field is required or not
'clear' => false, // add clear or not
'type' => 'text', // add field type
'class' => array('my-css'), // add class name
'priority' => '150'
);
return $fields;
}
/* Debiteutnummer back-end*/
add_action( 'woocommerce_checkout_update_order_meta', 'custom_save_new_checkout_field' );
function custom_save_new_checkout_field( $order_id ) {
if ( $_POST['debiteurnummer'] ) update_post_meta( $order_id, '_debiteurnummer', esc_attr( $_POST['debiteurnummer'] ) );
}
/* Debiteutnummer on order*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'custom_show_new_checkout_field_order', 10, 1 );
function custom_show_new_checkout_field_order( $order ) {
$order_id = $order->get_id();
if ( get_post_meta( $order_id, '_debiteurnummer', true ) ) echo '<p><strong>Debiteurnummer:</strong> ' . get_post_meta( $order_id, '_debiteurnummer', true ) . '</p>';
}
/* Debiteutnummer on email*/
add_action( 'woocommerce_email_after_order_table', 'custom_show_new_checkout_field_emails', 20, 4 );
function custom_show_new_checkout_field_emails( $order, $sent_to_admin, $plain_text, $email ) {
if ( get_post_meta( $order->get_id(), '_debiteurnummer', true ) ) echo '<p><strong>License Number:</strong> ' . get_post_meta( $order->get_id(), '_debiteurnummer', true ) . '</p>';
}
Does anybody had an solution or does somebody see what i'm doing wrong?

Yii2 - input search with auto-complete

I am using default Yii2 library for auto-complete. How can I make it, so it is reading values from DB while user is typing?
This is code I have so far, but query is done when the page is created:
echo AutoComplete::widget([
'name' => 'tradeName',
'model' => TradeNames::find()->select('name')->all(),
'options' => [
'class' => 'form-control'
],
'clientOptions' => [
'source' => array_column(TradeNames::find()->select('name')->asArray()->all(), 'name'),
},
],
]);
I followed this advice
jqueryui.com/autocomplete/#multiple and have written next code
<div id="autocomplete" class="ui-widget">
<?= \yii\jui\AutoComplete::widget([
'attribute' => 'attribute',
'name' => 'tradeName',
'clientOptions' => [
'source' => \Yii::$container->get('JsExpression',['function(request, response) {
response( $.ui.autocomplete.filter( window.dataAsArray, extractLast( request.term ) ) );
}']),
'select' => \Yii::$container->get('JsExpression',['function(event, ui) {
var terms = split( this.value );
terms.pop();
terms.push( ui.item.value );
terms.push( "" );
this.value = terms.join( ", " );
return false;
}']),
'focus' => \Yii::$container->get('JsExpression',['function() {
return false;
}']),
]
]) ?>
</div>
<script>
window.dataAsArray = ['item1', 'item2', 'item3'];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$(document).ready( function() {
$('#autocomplete').on('keydown', function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
});
});
</script>
maybe it help to someone
try this
use yii\jui\AutoComplete;
use yii\web\JsExpression;
<?php
$data = TradeNames::find()
->select(['name as value', 'name as label','id as id'])
->asArray()
->all();
echo 'Trade Names' .'<br>';
echo AutoComplete::widget([
'name' => 'tradeName',
'id' => 'trade_name',
'clientOptions' => [
'source' => $data,
// 'minLength'=>'3',
'autoFill'=>true,
'select' => new JsExpression("function( event, ui ) {
$('#memberssearch-family_name_id').val(ui.item.id);//#memberssearch-family_name_id is the id of hiddenInput.
}")],
]);
?>
<?= Html::activeHiddenInput($model, 'tradeName')?>

Zend2: Specify currency prefix?

In Zend2 you can do this:
<?php echo $this->currencyFormat(120, 'ZAR'); ?>
This will result in:
ZAR 120.00
However, I want to end up with:
R 120.00
How can I set the prefix to rather be the currency symbol, as apposed to the code? The following doesn't work (obviously):
<?php echo $this->currencyFormat(120, 'R'); ?>
Figured it out myself. Easy as this:
$helper->setCurrencyPattern('R #0.#');
So the complete code which allows me to control everything in one place (Module.php) is as follows:
class Module
{
public function getConfig()
{
return array(
'view_helpers' => array(
'factories' => array(
'currencyFormat' => function($sm)
{
$helper = new \Zend\I18n\View\Helper\CurrencyFormat;
$helper->setCurrencyCode("ZAR");
$helper->setLocale('us_ZA');
$helper->setCurrencyPattern('R #0.#');
return $helper;
},
)
),
);
}
}
Enjoy...

Twitter says "Could not authenticate you" when space inside a parameter

The code below works perfectly fine if, $searchterm = "Chinmay", but doesn't work correct, when the $searchterm has a space in it. I have tried many encoding and have no luck with it.
Section 1 - Getting the URL and Parameters
$searchterm = "Chinmay+Patel";
$params = array( "q" => $searchterm );
$url = 'https://api.twitter.com/1.1/users/search.json';
Section 2 - Building the Signature
$oauth = array(
'oauth_consumer_key' => \Config::get("oauth-4-laravel::consumers.Twitter.client_id"),
'oauth_nonce' => hash('SHA1', time()),
'oauth_signature' => '',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $this->twitter_user->access_token,
'oauth_version' => '1.0'
);
foreach ($oauth as $key => $value)
{
if (empty($value)) continue;
$oauth_vals[] = "{$key}={$value}";
}
if( !empty( $params ) ){
foreach ($params as $key => $value) {
if(empty($value)) continue;
$oauth_vals[] = "{$key}={$value}";
}
}
$base = 'GET&' . rawurlencode($url) . '&' . rawurlencode(implode('&', $oauth_vals) );// . '&'. implode( '&', $params);
$composite_key = rawurlencode(\Config::get("oauth-4-laravel::consumers.Twitter.client_secret")) . '&' . rawurlencode($this->twitter_user->secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base, $composite_key, true));
$oauth['oauth_signature'] = rawurlencode($oauth_signature);
Section 3 - Building the request header
foreach ($oauth as $key => $value)
{
$auth_header[] = "{$key}=\"{$value}\"";
}
$auth_header = implode(', ', $auth_header);
Section 4 - Building the url and making the request
if( !empty( $params ) ){
$url .= "?" . http_build_query( $params );
}
$verbose = fopen('php://temp', 'rw+');
$options = array(
CURLOPT_HTTPHEADER => array("Authorization: OAuth {$auth_header}"),
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTPGET => true,
// DEBUGGING
CURLOPT_VERBOSE => TRUE,
CURLOPT_STDERR => $verbose
);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json, true);
rewind($verbose);
Section 5 - Outputting the data
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
var_dump( $twitter_data );
What could be the issue? A little bit out of scope for the question, but this code doesn't work with multiple parameters either. For example, if I add the count parameter, it gives me the same error.

paypal access oauth login json_decode returned null

i have 2 PHP files, one index.php and the other one paypal.php.
The code for paypal.php is:
<?php
session_start();
$client_id = 'xxxxxxxxxxxx';
$client_secret = 'xxxxxxxxxxxxxxxxxxxx';
$scopes = 'email profile';
$app_return_url = 'http://xxx.com/xxx/paypal.php';
$nonce = time() . rand();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$paypal_auth_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?"
."client_id=".$client_id
."&response_type=code"
."&scope=".$scopes
."&nonce=".$nonce
."&state=".$_SESSION['state']
."&redirect_uri=".urlencode($app_return_url);
header("Location: $paypal_auth_url");
}else{
$token_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/tokenservice";
$postvals = "client_id=".$client_id
."&client_secret=".$client_secret
."&grant_type=authorization_code"
."&code=".$code;
$ch = curl_init($token_url);
$options = array(
CURLOPT_POST => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_POSTFIELDS => $postvals,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSLVERSION => 3
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
curl_close($ch);
$atoken = json_decode($response);
$profile_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/userinfo?"
."schema=openid"
."access_token=".$atoken->access_token;
$ch = curl_init($profile_url);
$options = array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSLVERSION => 3
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
curl_close($ch);
$profile= json_decode($response,true);
$_SESSION['paypal_user'] = "true";
$_SESSION['profile'] = $profile;
echo("<script> top.location.href='index.php'</script>");
}
?>
The code for index.php is:
<?php
session_start();
// LOGOUT
if ($_GET['logout'] == 'true'){
$_SESSION['paypal_user']="";
}
if (strlen($_SESSION['paypal_user'])){
// LOGGED USER
echo "<pre>";
print_r($_SESSION['profile']);
echo "</pre>";
echo "<br><BR> <a href='?logout=true'>LOGOUT</a>";
}else{
// LOGIN
?>
<a href='paypal.php' title='Paypal oAuth Login'>
<img src='https://www.paypalobjects.com/en_US/Marketing/i/btn/login-with-paypal-button.png'>
</a>
<?
}
?>
Any ideas why this code is not working? I tried var_dump json_decode and it returns null.
Thank you!
I may be wrong, but I believe you scopes need to be...
"scopes": "email https://uri.paypal.com/services/paypalattributes",
The URL is the profile
simply add '&' on before access token,he missed & symbol between two variables
$profile_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/userinfo?" ."schema=openid" ."**&**access_token=".$atoken->access_token;

Resources