Foros del Web » Creando para Internet » Sistemas de gestión de contenidos » WordPress »

Duda con imagen

Estas en el tema de Duda con imagen en el foro de WordPress en Foros del Web. Amigo, buenos días, tengo una duda, estoy intentando mostrar en mi página inicial el último aporte de x categorías pero necesito que me muestre un ...
  #1 (permalink)  
Antiguo 19/11/2012, 11:44
Avatar de el_tigre  
Fecha de Ingreso: febrero-2006
Ubicación: Perú
Mensajes: 1.044
Antigüedad: 18 años, 3 meses
Puntos: 8
De acuerdo Duda con imagen

Amigo, buenos días, tengo una duda, estoy intentando mostrar en mi página inicial el último aporte de x categorías pero necesito que me muestre un pequeño resumen y la imagen que esta tiene, .....he llegado a mostrar el pequeño resumen con su link pero no logro mostrar la imagen........¿cómo podría hacerlo?

Esta es mi web

  #2 (permalink)  
Antiguo 19/11/2012, 12:00
Avatar de Nekko
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Buenos Aires
Mensajes: 3.141
Antigüedad: 16 años, 1 mes
Puntos: 656
Respuesta: Duda con imagen

Lee sobre the_post_thumbnail().
__________________
Taller para crear themes wordpress desde cero | Presupuestos para trabajos particulares vía MP
  #3 (permalink)  
Antiguo 19/11/2012, 15:23
Avatar de el_tigre  
Fecha de Ingreso: febrero-2006
Ubicación: Perú
Mensajes: 1.044
Antigüedad: 18 años, 3 meses
Puntos: 8
Respuesta: Duda con imagen

Hi Nekko, yo la verdad ya lo había intentado con la función : the_post_thumbnail(). pero no tuve resultado alguno, parece que las imágenes se guardan de otra forma, yo me pregunta cómo hace el facebook por ejemplo para mostrarte la imagen con un resumen ¿cómo obtiene él código?.....esa es la idea.

  #4 (permalink)  
Antiguo 20/11/2012, 07:08
Avatar de Nekko
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Buenos Aires
Mensajes: 3.141
Antigüedad: 16 años, 1 mes
Puntos: 656
Respuesta: Duda con imagen

Podés usar un script externo que se llama timthumb, pero la verdad es que desde que WordPress ofrece the_post_thumbnail.. ¿para que agregar algo que ya está?

En tu functions.php añadí la siguiente línea que habilita la función.
Código PHP:
add_theme_support('post-thumbnails'); 
Para que tus imágenes puedan ser llamadas con dicha función, primero las tenés que marcar como destacadas. Si querés que agarre la primer imagen que encuentre en los posts, añadí el siguiente código en el functions.php de tu theme:

Código PHP:
function autoset_featured() {
          global 
$post;
          
$already_has_thumb has_post_thumbnail($post->ID);
              if (!
$already_has_thumb)  {
              
$attached_image get_children"post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
                          if (
$attached_image) {
                                foreach (
$attached_image as $attachment_id => $attachment) {
                                
set_post_thumbnail($post->ID$attachment_id);
                                }
                           }
                        }
      }  
//end function
add_action('the_post''autoset_featured');
add_action('save_post''autoset_featured');
add_action('draft_to_publish''autoset_featured');
add_action('new_to_publish''autoset_featured');
add_action('pending_to_publish''autoset_featured');
add_action('future_to_publish''autoset_featured'); 
Y lee sobre la función así como
http://codex.wordpress.org/Function_...add_image_size
__________________
Taller para crear themes wordpress desde cero | Presupuestos para trabajos particulares vía MP
  #5 (permalink)  
Antiguo 20/11/2012, 16:38
Avatar de el_tigre  
Fecha de Ingreso: febrero-2006
Ubicación: Perú
Mensajes: 1.044
Antigüedad: 18 años, 3 meses
Puntos: 8
Respuesta: Duda con imagen

Agregué esos código al fucntion.php pero al llamarlo en mi index....no he podido mostrar la imagen que acompaña al texto resumen......¿algo más falta?

Código PHP:

<?php 
if ( has_post_thumbnail() ) { 
  
the_post_thumbnail();

?>


                            <?php $my_query = new WP_Query('cat=35&showposts=1'); ?>

                <?php while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate $post->ID?> 

                <div class="Bt1"> 

                <a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a>

                </div>

                <?php the_content_limit('120'); ?>

                <?php endwhile;?>
  #6 (permalink)  
Antiguo 21/11/2012, 05:32
Avatar de Nekko
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Buenos Aires
Mensajes: 3.141
Antigüedad: 16 años, 1 mes
Puntos: 656
Respuesta: Duda con imagen

Colocalo dentro del loop, sino no va a funcionar.
__________________
Taller para crear themes wordpress desde cero | Presupuestos para trabajos particulares vía MP
  #7 (permalink)  
Antiguo 21/11/2012, 07:51
Avatar de el_tigre  
Fecha de Ingreso: febrero-2006
Ubicación: Perú
Mensajes: 1.044
Antigüedad: 18 años, 3 meses
Puntos: 8
Respuesta: Duda con imagen

Cita:
Iniciado por Nekko Ver Mensaje
Colocalo dentro del loop, sino no va a funcionar.
Lo probé así y nada de nada mi estimada Nekko

Código PHP:
<?php $my_query = new WP_Query('cat=35&showposts=1'); ?>

 <?php while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate $post->ID?> 

<?php if ( has_post_thumbnail() ) {   the_post_thumbnail();} ?>

 <div class="Bt1"> 
 <a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a>
</div>
 <?php the_content_limit('120'); ?>

  <?php endwhile;?>
  #8 (permalink)  
Antiguo 21/11/2012, 09:17
Avatar de Nekko
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Buenos Aires
Mensajes: 3.141
Antigüedad: 16 años, 1 mes
Puntos: 656
Respuesta: Duda con imagen

Definí una imagen destacada, el snippet no aplica para contenidos que subiste en el pasado.
__________________
Taller para crear themes wordpress desde cero | Presupuestos para trabajos particulares vía MP
  #9 (permalink)  
Antiguo 21/11/2012, 10:23
Avatar de el_tigre  
Fecha de Ingreso: febrero-2006
Ubicación: Perú
Mensajes: 1.044
Antigüedad: 18 años, 3 meses
Puntos: 8
De acuerdo Respuesta: Duda con imagen

Nekko, qué pasa si la imagen lo subo a un servidor público de imágenes o cosas así?, es decir, yo no tengo la imagen en mi host.....además destacar imágenes es "un trabajo extra".....¿no existe forma que jale la imagen que tiene el post como lo hace el facebook o el mismo plugin...."Random post" ?

Saludos
  #10 (permalink)  
Antiguo 21/11/2012, 10:29
Avatar de Nekko
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Buenos Aires
Mensajes: 3.141
Antigüedad: 16 años, 1 mes
Puntos: 656
Respuesta: Duda con imagen

Usá un custom field para traer la url de la imagen.

Código PHP:
Ver original
  1. <img src="<?php echo get_post_meta(get_the_id(), 'url_image', TRUE); ?>" width="500" height="100" />
Pero que se yo, no me parece muy prolijo.
__________________
Taller para crear themes wordpress desde cero | Presupuestos para trabajos particulares vía MP
  #11 (permalink)  
Antiguo 21/11/2012, 12:22
Avatar de el_tigre  
Fecha de Ingreso: febrero-2006
Ubicación: Perú
Mensajes: 1.044
Antigüedad: 18 años, 3 meses
Puntos: 8
Respuesta: Duda con imagen

No he podido usar ni eso último Nekko........me falta mucho sobre programación...... este es el código de advanced Random post

Código PHP:
<?php
class yg_adv_random_posts extends WP_Widget {
    function 
yg_adv_random_posts() {     
     
$widget_ops = array('description' => __('Shows Random Posts. You can customize it easily.''adv-rnd-posts') );
     
//Create widget
     
$this->WP_Widget('advancedrandomposts'__('Advanced Random Posts''adv-rnd-posts'), $widget_ops);
    }

  function 
widget($args$instance) {
             
extract($argsEXTR_SKIP);
            echo 
$before_widget;
            
$title = empty($instance['title']) ? __('Random Posts''adv-rnd-posts') : apply_filters('widget_title'$instance['title']);
            
$parameters = array(
              
'title' => $title,
                
'limit' => (int) $instance['show-num'],
                (
omitidos para ahorrar espacio)
                
'w' => (int) $instance['width'],
                
'h' => (int) $instance['height'],
                
'firstimage' => (bool) $instance['firstimage'],
                
'atimage' =>(bool) $instance['atimage'],
                
'defimage' => esc_url($instance['defimage'])
            );

            if ( !empty( 
$title ) ) {
            echo 
$before_title $title $after_title;
            };
        
//print random posts
                
yg_randomposts($parameters);
            echo 
$after_widget;
  } 
//end of widget
    
    //Update widget options
  
function update($new_instance$old_instance) {

        
$instance $old_instance;
        
//get old variables
        
(omitidos para ahorrar espacio)
        
$instance['firstimage'] = $new_instance['first-image'] ? 0;
        
$instance['atimage'] = $new_instance['atimage'] ? 0;
        
$instance['defimage'] = esc_url($new_instance['def-image']);
        return 
$instance;
  } 
//end of update
    //Widget options form
  
function form($instance) {
        
$instance wp_parse_args( (array) $instance, array( 'title' => __('Advanced Random Posts','adv-rnd-posts'), 'show-num' => 10'excerpt-length' => 0'actcat' => 0'cats' => '''cus-field' => '''width' => '''height' => '''firstimage' => 0'atimage' => 0,'defimage'=>'' ) );
        (
omitidos para ahorrar espacio)
        
$firstimage = (bool) $instance['firstimage'];
        
$atimage = (bool) $instance['atimage'];
        
$defimage esc_url($instance['defimage']);
        
?>
        <p>
           <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:');?> 
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title?>" />
           </label>
        </p>
        (omitidos para ahorrar espacio)
        <p>
          <label for="<?php echo $this->get_field_id('cus-field'); ?>"><?php _e('Thumbnail Custom Field Name:''adv-rnd-posts');?> 
          <input id="<?php echo $this->get_field_id('cus-field'); ?>" name="<?php echo $this->get_field_name('cus-field'); ?>" type="text" value="<?php echo $cus_field?>" size ="20" /> 
          </label><br />
          <label for="<?php echo $this->get_field_id('width'); ?>"><?php _e('Width:''adv-rnd-posts');?> <input id="<?php echo $this->get_field_id('width'); ?>" name="<?php echo $this->get_field_name('width'); ?>" type="text" value="<?php echo $width?>" size ="3" /></label>px<br />
            <label for="<?php echo $this->get_field_id('height'); ?>"><?php _e('Height:''adv-rnd-posts');?> <input id="<?php echo $this->get_field_id('height'); ?>" name="<?php echo $this->get_field_name('height'); ?>" type="text" value="<?php echo $height?>" size ="3" /></label>px
      </p>
        <p>
            <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('first-image'); ?>" name="<?php echo $this->get_field_name('first-image'); ?>"<?php checked$firstimage ); ?> />
            <label for="<?php echo $this->get_field_id('first-image'); ?>"><?php _e('Get first image of post''adv-rnd-posts');?></label>
        </p>
        <p>
            <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('atimage'); ?>" name="<?php echo $this->get_field_name('atimage'); ?>"<?php checked$atimage ); ?> />
            <label for="<?php echo $this->get_field_id('atimage'); ?>"><?php _e('Get first attached image of post''adv-rnd-posts');?></label>
        </p>
      <p>
          <label for="<?php echo $this->get_field_id('def-image'); ?>"><?php _e('Default image:''adv-rnd-posts');?> 
          <input class="widefat" id="<?php echo $this->get_field_id('def-image'); ?>" name="<?php echo $this->get_field_name('def-image'); ?>" type="text" value="<?php echo $defimage?>" /><br />
            <small>(<?php _e('if there is no thumbnail, use this''adv-rnd-posts');?></small>
          </label>
      </p>    
      <p>
          <label for="<?php echo $this->get_field_id('cats'); ?>"><?php _e('Categories:''adv-rnd-posts');?> 
          <input class="widefat" id="<?php echo $this->get_field_id('cats'); ?>" name="<?php echo $this->get_field_name('cats'); ?>" type="text" value="<?php echo $cats?>" /><br />
            <small>(<?php _e('Category IDs, separated by commas.''adv-rnd-posts');?>)</small>
          </label>
      </p>
        <p>
            <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('actcat'); ?>" name="<?php echo $this->get_field_name('actcat'); ?>"<?php checked$actcat ); ?> />
            <label for="<?php echo $this->get_field_id('actcat'); ?>"> <?php _e('Get posts from current category''adv-rnd-posts');?></label>
        </p>
   <?php
  
//end of form
}
add_action'widgets_init'create_function('''return register_widget("yg_adv_random_posts");') );
//Register Widget
 // Show random posts function
 
function yg_randomposts($args '') {
  global 
$wpdb;
    
$defaults = array('limit' => 10'excerpt' => 0'actcat' => 0'cats'=>'''cusfield' =>'''w' => 48'h' => 48'firstimage' => 0);
    
$args wp_parse_args$args$defaults );
    
extract($args);
    
$limit = (int) abs($limit);
    
$firstimage = (bool) $firstimage;
    
$w = (int) $w;
    
$h = (int) $h;
    
$excerptlength = (int) abs($excerpt);
    
$excerpt '';
    
$cats str_replace(" """esc_attr($cats));
    if ((
$limit ) || ($limit 20)) $limit 10;
    if ((
$actcat) && (is_category())) {
     
$cats get_query_var('cat');
    }
    if ((
$actcat) && (is_single())) {
     
$cats '';
     foreach (
get_the_category() as $catt) {
       
$cats .= $catt->cat_ID.' '
     }
     
$cats str_replace(" "","trim($cats));
    }
    if (!
intval($cats)) $cats='';
    
$query "cat=$cats&showposts=$limit&orderby=rand";
    
$rnd_posts get_posts($query); //get posts by random
    
$postlist '';
    
$height $h ' height = "' $h .'"' '';
    
$width $w ' width = "' $w '"' '';
    foreach (
$rnd_posts as $post) {
          
$post_title htmlspecialchars(stripslashes($post->post_title));
            if (
$excerptlength) {
                
$excerpt $post->post_excerpt;
                if ( 
'' == $excerpt ) {
                    
$text $post->post_content;
                    
$text strip_shortcodes$text );
                    
$text str_replace(']]>'']]&gt;'$text);
                    
$text strip_tags($text);
                    
$excerpt_length 100;
                    
$words explode(' '$text$excerpt_length 1);
                    if (
count($words) > $excerpt_length) {
                        
array_pop($words);
                        
$text implode(' '$words);
                    }
$excerpt $text;
                }
              if(
strlen($excerpt) > $excerptlength) {
                 
$excerpt mb_substr($excerpt0$excerptlength) . '...';
                }
                
$excerpt ': ' $excerpt;
            }
            
$image '';
            
$img '';
            if (
$cusfield) {
             
$cusfield esc_attr($cusfield);
             
$img get_post_meta($post->ID$cusfieldtrue);
            }
             if (!
$img && $firstimage) {
               
$match_count preg_match_all("/<img[^']*?src=\"([^']*?)\"[^']*?>/"$post->post_content$match_arrayPREG_PATTERN_ORDER);        
               
$img $match_array[1][0];
             }
           if (!
$img && $atimage) { 
                 
$p = array(
                  
'post_type' => 'attachment',
                  
'post_mime_type' => 'image',
                  
'numberposts' => 1,
                  
'order' => 'ASC',
                  
'orderby' => 'menu_order ID',
                  
'post_status' => null,
                  
'post_parent' => $post->ID
                 
);
                 
$attachments get_posts($p);
                 if (
$attachments) {
                   
$imgsrc wp_get_attachment_image_src($attachments[0]->ID'thumbnail');
                   
$img $imgsrc[0];
                 }
                }
             if (!
$img && $defimage)
              
$img $defimage;
             if (
$img)
        
$image '<title="' $post_title '" img src="' $img '"  class="random-posts-thumb"' $width $height ' />';
    
$image '<img src="' $img '" title="' $post_title '" class="random-posts-thumb"' $width $height ' />';            
      
$postlist .= "<a href=\"" get_permalink($post->ID) . "\" title=\""$post_title ."\" >$image" $post_title ."</a>$excerpt\n";
    } echo 
'<ul class="advanced-random-posts">';        
    echo 
$postlist;
        echo 
'</ul>';
 }
?>
¿no es posible sacar algo de acá?
  #12 (permalink)  
Antiguo 21/11/2012, 12:42
Avatar de Nekko
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Buenos Aires
Mensajes: 3.141
Antigüedad: 16 años, 1 mes
Puntos: 656
Respuesta: Duda con imagen

Mira te recomiendo armarte de paciencia y leer para aprender. El "copy&paste" no es el objetivo de este foro, la idea es que aprendas y no que nosotros te hagamos el trabajo.

Por favor, tomate tu tiempo para analizar las cosas que te pasé y el uso del bucle en WordPress. Si seguís sin encontrarle la vuelta, considerá contratar un programador.
__________________
Taller para crear themes wordpress desde cero | Presupuestos para trabajos particulares vía MP

Etiquetas: página
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 00:26.