I'm displaying the userpicture on a node with this code here:
<?php
$user_load = user_load($node->uid);
$imgtag = theme('imagecache', 'avatar_node', $user_load->picture, $user_load->name, $user_load->name);
$attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
print l($imgtag, 'u/'.$user_load->name, $attributes);
?>
This works great, except if the user doesn't have a picture, in which case it looks strange.
How do I load the default picture if the user doesn't have a picture.
I don't believe I have access to $picture in this block.
Thanks in advance.
$user_load = user_load($node->uid);
$picture = $user_load->picture ? $user_load->picture : variable_get('user_picture_default', ''); //
$imgtag = theme('imagecache', 'avatar_node', $picture, $user_load->name, $user_load->name);
$attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
print l($imgtag, 'u/'.$user_load->name, $attributes);
if you copy default picture to files directory, you can determine it via http://api.drupal.org/api/function/file_directory_path/6
This is what I'm using for a similar situation:
if (!empty($user->picture) && file_exists($user->picture)) {
$picture = file_create_url($user->picture);
}
else if (variable_get('user_picture_default', '')) {
$picture = variable_get('user_picture_default', '');
}
if (isset($picture)) {
$alt = t("#user's picture", array('#user' => $user->name ? $user->name : variable_get('anonymous', t('Anonymous'))));
$picture = theme('image', $picture, $alt, $alt, '', FALSE);
if (!empty($user->uid) && user_access('access user profiles')) {
$attributes = array(
'attributes' => array('title' => t('View user profile.')),
'html' => TRUE,
);
echo l($picture, "user/$user->uid", $attributes);
}
}
It is adapted from http://api.drupal.org/api/drupal/modules%21user%21user.module/function/template_preprocess_user_picture/6
In Drupal 7 I use:
global $user;
file_create_url( file_load($user->picture)->uri)
Related
WP tends to load a lot of things with ajax admin, but what I need is to only load it to use basic ajax with my own calls and functions.
This posts says:
<?php
//mimic the actuall admin-ajax
define('DOING_AJAX', true);
if (!isset( $_POST['action']))
die('-1');
//make sure you update this line
//to the relative location of the wp-load.php
require_once('../../../../../wp-load.php');
//Typical headers
header('Content-Type: text/html');
send_nosniff_header();
//Disable caching
header('Cache-Control: no-cache');
header('Pragma: no-cache');
$action = esc_attr(trim($_POST['action']));
//A bit of security
$allowed_actions = array(
'my_allow_action_1',
'my_allow_action_2',
'my_allow_action_3',
'my_allow_action_4',
'my_allow_action_5'
);
if(in_array($action, $allowed_actions)){
if(is_user_logged_in())
do_action('MY_AJAX_HANDLER_'.$action);
else
do_action('MY_AJAX_HANDLER_nopriv_'.$action);
}
else{
die('-1');
}
And it says:
Next we Only need to hook our callbacks to this handler like so:
//For logged in users
add_action('MY_AJAX_HANDLER_{$action_name}','function_callback_name');
//For logged out users
add_action('MY_AJAX_HANDLER_nopriv_{$action_name}','function_callback_name');
Finally says :
jQuery(document).ready(function($){
var data={
action:'action_name',
otherData: 'otherValue'
};
$.post('http://url/to/your/MY_CUSTOM_AJAX.php', data, function(response){
alert(response);
});
});
But I got confused, as I don't know what it means with SOME CUSTOM TEXT or how it is handling the variables etc, this is how I currently do:
function.php
add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' );
add_action('wp_ajax_data_fetch' , 'data_fetch');
function data_fetch(){
$dates = $_POST['dates'];
$dates = explode(',', $dates);
$args = array(
'meta_query' => array(
array(
'key' => 'anno',
'value' => array($dates[0], $dates[1]),
'compare' => 'BETWEEN',
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'type' => 'NUMERIC'
),
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ):
$coordinates = [];
$links = [];
while( $query->have_posts() ) : $query->the_post();
$id = get_the_ID();
$location = get_field('location');
$lat = $location['lat'];
$lng = $location['lng'];
$title = get_the_title($id);
if ( ! add_post_meta( $id, 'latitude', $lat, true) ) {
delete_post_meta($id, 'latitude');
update_post_meta($id, 'latitude', $lat, true);
}
if ( ! add_post_meta( $id, 'longitude', $lng, true) ) {
delete_post_meta($id, 'longitude');
update_post_meta($id, 'longitude', $lng, true);
}
$latitude = get_field('latitude');
$longitude = get_field('longitude');
$coordinates[] = $latitude.", ".$longitude;
$links[] = get_permalink();
$anno = get_field('anno');
$site[] = get_field("site_name", "option", true);
$contentProprierty[] = array("links"=>$links, "coordinates"=>$coordinates, "anno"=>$anno, "ids"=>$id, "site"=>$site, "title"=>$title);
endwhile;
echo json_encode($contentProprierty);
die;
endif;
wp_die();
}
JS in front end:
var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
$.ajax({
url : ajax_url,
type: 'post',
dataType: 'json',
data: {
action: 'data_fetch', dates: datesSearch
},
success: function(data) {
for (var i = 0; i < data.length; i++) {
coords.push(data[i].coordinates[i]);
links.push(data[i].links[i]);
years.push([data[i].anno]);
ids.push(data[i].ids);
titles.push(data[i].title);
currentSite.push("curr");
site.push(thisSiteName);
};
}
});
How would I implement the custom ajax in order not to load the whole thing wp does with its own ajax admin?
add_action('MY_AJAX_HANDLER_{$action_name}','function_callback_name');
//For logged out users
add_action('MY_AJAX_HANDLER_nopriv_{$action_name}','function_callback_name');
These action hooks only call data related to your current ajax function nothing else you can use wp_nonce_field to secure your function from hacking and securing the site. inside the function.
Situation
I have a custom module that is using hook_field_formatter_info() to add an "fancy" option to the image field in the manage display of a content type. When this option is chosen I want to be able to surround the ENTIRE field in custom divs and markup. I want the solution to be a hook in my custom module and not a template override.
Process
A user wants the display of an image field to be the "fancy" option. They check it in the drop down and click save from the content types Manage Display admin page. Now on that content type node there should be custom markup surrounding the entire field even if there are multiple images, the new markup should surround ALL the images and not each individual image.
hook_field_formatter_view
hook_field_formatter_view seems to demand it's output be an array and I can't seem to be able to wrap the output in a div.
Template overrides
I can't just make a field.tpl.php for the specific field because like I initially mentioned I need to be able to switch themes and the module still work like normal. Unless there is a way to get my module to override any field where said field has hook_field_formatter_info() set specifically.
/**
* Implements hook_field_formatter_view().
*/
function bootstrap_modal_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
foreach ($items as $delta => $item) {
if ($index === NULL || $index === $delta) {
$element[$delta] = array(
'#theme' => 'bootstrap_modal_image_formatter',
'#item' => $item,
'#entity_type' => $entity_type,
'#entity' => $entity,
'#node' => $entity, // Left for legacy support.
'#field' => $field,
'#display_settings' => $display['settings'],
'#delta' => $delta,
);
}
}
// $element = '<div id="CUSTOMDIVSTUFF">' . $element . '</div>';
return $element;
}
And here is the #theme function:
function theme_bootstrap_modal_image_formatter($variables) {
$item = $variables['item'];
$entity_type = $variables['entity_type'];
$entity = $variables['entity'];
$field = $variables['field'];
$settings = $variables['display_settings'];
$image = array(
'path' => $item['uri'],
'alt' => isset($item['alt']) ? $item['alt'] : '',
'title' => isset($item['title']) ? $item['title'] : '',
'style_name' => $settings['bootstrap_modal_node_style'],
);
if (isset($item['width']) && isset($item['height'])) {
$image['width'] = $item['width'];
$image['height'] = $item['height'];
}
if (isset($item['attributes'])) {
$image['attributes'] = $item['attributes'];
}
// Allow image attributes to be overridden.
if (isset($variables['item']['override']['attributes'])) {
foreach (array('width', 'height', 'alt', 'title') as $key) {
if (isset($variables['item']['override']['attributes'][$key])) {
$image[$key] = $variables['item']['override']['attributes'][$key];
unset($variables['item']['override']['attributes'][$key]);
}
}
if (isset($image['attributes'])) {
$image['attributes'] = $variables['item']['override']['attributes'] + $image['attributes'];
}
else {
$image['attributes'] = $variables['item']['override']['attributes'];
}
}
$entity_title = entity_label($entity_type, $entity);
if ($style_name = $settings['bootstrap_modal_image_style']) {
$path = image_style_url($style_name, $image['path']);
}
else {
$path = file_create_url($image['path']);
}
$caption = 'some value';
$gallery_id = 'some value';
return theme('bootstrap_modal_imagefield', array('image' => $image, 'path' => $path, 'title' => $caption, 'gid' => $gallery_id));
}
Been working on this for days, I'm drowning here.
This is possible via HOOK_process_field(). Use this hook to define a new template file for your field by adding it to theme_hook_suggestions array (place the template file in your module directory, because you wanted to change the theme -as you mentioned-). More info about field template suggestions.
Then, you will need to add the module path to drupal theme registry, so it picks up the template file. Demo.
I found out it was:
function bootstrap_modal_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array(
'#prefix' => '<div class="wrapper">',
'#suffix' => '</div>',
);
I've been trying to get this seemingly easy peace of code to work.
I'm loading rss from a wordpress site and it all works fine except for the thumbnails. Since in the XML they are set as an attribute instead of a nodeValue i can't seem to get import them. (i've really tried a lot)
$rss = new DOMDocument();
$rss->load('http://goalprogramme.wordpress.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
// in XML it looks like <media:thumbnail url="http://goalprogramme.files.wordpress.com/2014/01/dsc_0227.jpg?w=150"/>
//echo $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url');
//push items
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
'thumbnail' => $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url') // this line doesn't work !!!
);
array_push($feed, $item);
}
Any help would be greatly appreciated.
Thanks so much in advance!
Hours later i've created another piece of code that does work. If anyone needs it it, here it is:
$feed_array = array();
$feed = simplexml_load_file('http://goalprogramme.wordpress.com/feed/');
foreach ($feed->channel->item as $item) {
$title = (string) $item->title;
$description = (string) $item->description;
$link = (string) $item->link;
$date = (string) $item->date;
if ($media = $item->children('media', TRUE)) {
if ($media->thumbnail) {
$attributes = $media->thumbnail->attributes();
$thumbnail = (string)$attributes['url'];
}
}
$item = array (
'title' => $title ,
'desc' => $description,
'link' => $link,
'date' => $date,
'thumbnail' => $thumbnail
);
array_push($feed_array, $item);
}
Not sure where the problem is in the following form used in a template file in Drupal7. Help is highly appreciated. The problems are the following:
1. The variables $title and $surname are not passed over to the form's default value.
=> Error Message: Notice: Undefined variable: title in form_user_information()
=> Error Message: Notice: Undefined variable: surname in form_user_information()
2. There's a Warning: strpos() expects parameter 1 to be string, array given in drupal_strip_dangerous_protocols()
Thanks in advance.
<?php
//Load User data:
global $user;
$uid = $user->uid;
$account = user_load($uid);
//Get User data:
$title = 'Mrs.';
print $title . '<br><br>'; //Result: Value is printed and not empty!
$surname = check_plain($account->field_vorname['und']['0']['value']);
//$surname = 'Tom';
print $surname . '<br><br>'; //Result: Both values are printed and are not empty!
function form_user_information($form, &$form_state) {
//Form
$form['#action'][] = request_uri();
$form['#id'][] = 'form_user_information';
$form['#validate'][] = 'form_user_information_validators';
$form['#submit'][] = 'form_user_information_submit';
$form['#prefix'] = '<div id="form_user_information">';
$form['#suffix'] = '</div>';
//Select-Field: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#select
$form['Title'] = array(
'#type' => 'select',
'#title' => t('Title'),
'#options' => array(
'Frau' => t('Mr.'),
'Herr' => t('Mrs.'),
),
'#default_value' => $title,
);
$form['surname'] = array(
'#type' => 'textfield',
'#maxlength' => 50,
'#size' => 40,
'#required' => TRUE,
'#title' => t('Surname'),
//'#attributes' => array('placeholder' => $surname),
'#default_value' => $surname,
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => 'Confirm data');
return $form;
}
//print form
$form = drupal_get_form('form_user_information');
print drupal_render($form);
//Form Validation:
function form_user_information_validators($form, &$form_state) {
if ($form_state['values']['surname'] == '') {
form_set_error('surname', t('Please enter your surname.'));
}
}
//Form Submit:
function form_user_information_submit($form, &$form_state) {
//...
}
//get form information
echo "<pre>".print_r($form,true)."</pre>";
?>
1) Set the global variables $title and $surname with global scope:
//Get User data:
$global $title = ...
$global $surname = ...
Otherwise set all these variables (including $user) inside the function form_user_information which is the best practice.
I would also suggest not use $title as variable name because it may cause problems with already defined $title of the $page variable. Instead use something like $user_title.
2) Which line does this come from?
Guess this issue can be closed. See the 2 comments. Thanks Theodoros for your help.
I have form with file upload element. This file (image) must be user picture, but it not set.
form:
$form['f']['step4']['file_e'] = array(
'#title' => t('Image'),
'#type' => 'managed_file',
'#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
'#upload_location' => 'public://images/',
);
validate
function fill_up_profile_form_validate($form, &$form_state) {
global $user;
if (isset($form['f']['actions']['submit']['#value']) && $form_state['triggering_element']['#value'] == $form['f']['actions']['submit']['#value']) {
$file = file_load($form_state['values']['f']['step4']['file_e']);
$validators = array(
'file_validate_is_image' => array(),
'file_validate_size' => array(1 * 1024 * 1024),
);
$errors = file_validate($file, $validators);
if (!empty($errors)) {
$message = '';
foreach ($errors as $error)
$message .= $error . '<br/>';
form_set_error('Error!', $message);
} else {
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
$edit['picture'] = $file;
user_save($user, $edit);
}
}
}
Thank you for your help.
You should try with $form_state instead of $form. $form_state contains the submitted values! Also, with Drupal 7.x, you can not get the values by simply using $form_state['values']['f']['step4']['file_e']! Just do a echo "<pre>"; print_R($form_state); echo "</pre>"; to learn the correct structure of the array!
Also have a look at this code: http://ly2.in/hBMxPK