• Resolved vicetias

    (@vicetias)


    Hola Héctor, por tu nombre imagino que hablas espa?ol así que espero que puedas responderme.

    Resulta que mi template tiene este típico código para contar visitas (que no es muy efectivo por cierto):

    if ( !function_exists( 'getCrunchifyPostViews' ) ) {
    function getCrunchifyPostViews($postID){
        $count_key = 'post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count==''){
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
            return "0 View";
        }
        return $count.' Views';
    }
    }
    
    if ( !function_exists( 'setCrunchifyPostViews' ) ) {
    function setCrunchifyPostViews($postID) {
        $count_key = 'post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count==''){
            $count = 0;
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
        }else{
            $count++;
            update_post_meta($postID, $count_key, $count);
        }
    }
    }

    Ok, lo que quiero es saber si se puede modificar algo en ese código y usar wpp_get_views para que cuente las visitas desde tu plugin y sea rellenado en el campo post_views_count. Si se puede no sé cómo podría implementarlo para que no salga error. Puedes ayudarme?

    • This topic was modified 7 years, 4 months ago by vicetias.
Viewing 15 replies - 1 through 15 (of 15 total)
  • Plugin Author Hector Cabrera

    (@hcabrera)

    Hola @vicetias!

    Hablo espa?ol pero por las reglas del foro debemos utilizar el inglés ??

    Yes, it’s possible to modify that code to use WPP’s views data instead. I’ll help you out once I get back from work (it’s 7 am here, so that’ll be in a few hours.)

    Plugin Author Hector Cabrera

    (@hcabrera)

    Alright, as promised here’s the updated code:

    if ( !function_exists( 'getCrunchifyPostViews' ) ) {
        function getCrunchifyPostViews( $postID ){
    
            // Views meta key
            $count_key = 'post_views_count';
    
            // Get post meta
            $count = get_post_meta( $postID, $count_key, true );
    
            // Views meta not found, this post 
            // doesn't have any registered views yet
            if ( '' == $count ) {
                $count = 0;
            }
    
            return ( 1 == $count ) ? '1 view' : $count . 'views';
    
        }
    }
    
    if ( !function_exists( 'setCrunchifyPostViews' ) ) {
        function setCrunchifyPostViews( $postID ) {
    
            // Get views count
            $count = wpp_get_views( $postID );
    
            // Views meta key
            $count_key = 'post_views_count';
    
            // Save / update post meta
            update_post_meta( $postID, $count_key, $count );
    
        }
    }

    I’ve simplified it a bit too and it’ll still work as intended.

    • This reply was modified 7 years, 4 months ago by Hector Cabrera. Reason: Updated code comments
    Thread Starter vicetias

    (@vicetias)

    Ok ok, thank you so much!! (pero odio un poco el inglés y no sé mucho hablarlo, así trataré de escribir en spanglish jaja)

    Sabes, no dio error el código, pero se quedan atascadas algunas y no cuenta las nuevas visitas, creo que se demora más de la cuenta porque comparo las estadísticas del plugin con post_views_count y siempre está por debajo :/

    • This reply was modified 7 years, 4 months ago by vicetias.
    Plugin Author Hector Cabrera

    (@hcabrera)

    Ok ok, thank you so much!! (pero odio un poco el inglés y no sé mucho hablarlo, así trataré de escribir en spanglish jaja)

    Unfortunately forum rules state we should communicate in english, so let’s try to do our best ??

    … se quedan atascadas algunas y no cuenta las nuevas visitas …

    Are you using a caching plugin by any chance?

    Thread Starter vicetias

    (@vicetias)

    My bad sorry, just checked again and it take a bit to update but the views are now synchronized! Thanks!

    And now, popular widget of my theme has the “freshness” filter you have on your plugin but if is possible, I need to add the default range too (no matter the date a post was published, you know).

    If you can help me with this, I’ll be totally grateful.

    This is the code:

    <?php
    /**
     * Plugin Name: Popular Posts Widget
     */
    
    add_action( 'widgets_init', 'mvp_pop_load_widgets' );
    
    function mvp_pop_load_widgets() {
    	register_widget( 'mvp_pop_widget' );
    }
    
    class mvp_pop_widget extends WP_Widget {
    
    	/**
    	 * Widget setup.
    	 */
    	function mvp_pop_widget() {
    		/* Widget settings. */
    		$widget_ops = array( 'classname' => 'mvp_pop_widget', 'description' => esc_html__('A widget that displays a list of popular posts within a time period of your choice.', 'click-mag') );
    
    		/* Widget control settings. */
    		$control_ops = array( 'width' => 250, 'height' => 350, 'id_base' => 'mvp_pop_widget' );
    
    		/* Create the widget. */
    		$this->__construct( 'mvp_pop_widget', esc_html__('Click Mag: Popular Posts Widget', 'click-mag'), $widget_ops, $control_ops );
    	}
    
    	/**
    	 * How to display the widget on the screen.
    	 */
    	function widget( $args, $instance ) {
    		extract( $args );
    
    		/* Our variables from the widget settings. */
    		global $post;
    		$title = apply_filters('widget_title', $instance['title'] );
    		$popular_days = $instance['popular_days'];
    		$number = $instance['number'];
    
    		/* Before widget (defined by themes). */
    		echo $before_widget;
    
    		/* Display the widget title if one was input (before and after defined by themes). */
    		if ( $title )
    			echo $before_title . $title . $after_title;
    
    		?>
    
    		<div class="mvp-trend-widget-wrap left relative">
    			<?php $popular_days_ago = "$popular_days days ago"; $recent = new WP_Query(array( 'posts_per_page' => $number, 'orderby' => 'meta_value_num', 'order' => 'DESC', 'meta_key' => 'post_views_count', 'date_query' => array( array( 'after' => $popular_days_ago )) )); while($recent->have_posts()) : $recent->the_post(); ?>
    			<div class="mvp-trend-widget-story left relative">
    				<?php if (  (function_exists('has_post_thumbnail')) && (has_post_thumbnail())  ) { ?>
    					<div class="mvp-100img-out right relative">
    						<a href="<?php the_permalink(); ?>" rel="bookmark">
    						<div class="mvp-trend-widget-img left relative">
    							<?php the_post_thumbnail('mvp-small-thumb'); ?>
    						</div><!--mvp-trend-widget-img-->
    						</a>
    						<div class="mvp-100img-in">
    							<div class="mvp-trend-widget-text left relative">
    								<h3 class="mvp-main-blog-cat left"><span class="mvp-main-blog-cat left"><?php $category = get_the_category(); echo esc_html( $category[0]->cat_name ); ?></span></h3>
    								<a href="<?php the_permalink(); ?>" rel="bookmark"><h2><?php the_title(); ?></h2></a>
    							</div><!--mvp-trend-widget-text-->
    						</div><!--mvp-100img-in-->
    						<div class="mvp-story-share-wrap">
    							<span class="mvp-story-share-but fa fa-share fa-2"></span>
    							<div class="mvp-story-share-cont">
    								<a href="#" onclick="window.open('https://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>', 'facebookShare', 'width=626,height=436'); return false;" title="Share on Facebook"><span class="mvp-story-share-fb fa fa-facebook fa-2"></span></a>
    								<a href="#" onclick="window.open('https://twitter.com/share?text=<?php the_title(); ?> -&url=<?php the_permalink() ?>', 'twitterShare', 'width=626,height=436'); return false;" title="Tweet This Post"><span class="mvp-story-share-twit fa fa-twitter fa-2"></span></a>
    								<a href="#" onclick="window.open('https://pinterest.com/pin/create/button/?url=<?php the_permalink();?>&media=<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'post-thumb' ); echo esc_url( $thumb['0'] ); ?>&description=<?php the_title(); ?>', 'pinterestShare', 'width=750,height=350'); return false;" title="Pin This Post"><span class="mvp-story-share-pin fa fa-pinterest-p fa-2"></span></a>
    							</div><!--mvp-story-share-cont-->
    						</div><!--mvp-story-share-wrap-->
    					</div><!--mvp-100img-out-->
    				<?php } else { ?>
    					<div class="mvp-trend-widget-text left relative">
    						<h3 class="mvp-main-blog-cat left"><span class="mvp-main-blog-cat left"><?php $category = get_the_category(); echo esc_html( $category[0]->cat_name ); ?></span></h3>
    						<a href="<?php the_permalink(); ?>" rel="bookmark"><h2><?php the_title(); ?></h2></a>
    					</div><!--mvp-trend-widget-text-->
    				<?php } ?>
    			</div><!--mvp-trend-widget-story-->
    			<?php endwhile; wp_reset_postdata(); ?>
    		</div><!--mvp-trend-widget-wrap-->
    
    		<?php
    
    		/* After widget (defined by themes). */
    		echo $after_widget;
    
    	}
    
    	/**
    	 * Update the widget settings.
    	 */
    	function update( $new_instance, $old_instance ) {
    		$instance = $old_instance;
    
    		/* Strip tags for title and name to remove HTML (important for text inputs). */
    		$instance['title'] = strip_tags( $new_instance['title'] );
    		$instance['popular_days'] = strip_tags( $new_instance['popular_days'] );
    		$instance['number'] = strip_tags( $new_instance['number'] );
    
    		return $instance;
    	}
    
    	function form( $instance ) {
    
    		/* Set up some default widget settings. */
    		$defaults = array( 'title' => 'Title', 'number' => 5, 'popular_days' => 30 );
    		$instance = wp_parse_args( (array) $instance, $defaults ); ?>
    
    		<!-- Widget Title: Text Input -->
    		<p>
    			<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
    			<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:90%;" />
    		</p>
    
    		<!-- Number of days -->
    		<p>
    			<label for="<?php echo $this->get_field_id( 'popular_days' ); ?>">Number of days to use for Popular Posts:</label>
    			<input id="<?php echo $this->get_field_id( 'popular_days' ); ?>" name="<?php echo $this->get_field_name( 'popular_days' ); ?>" value="<?php echo $instance['popular_days']; ?>" size="3" />
    		</p>
    
    		<!-- Number of posts -->
    		<p>
    			<label for="<?php echo $this->get_field_id( 'number' ); ?>">Number of posts to display:</label>
    			<input id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" value="<?php echo $instance['number']; ?>" size="3" />
    		</p>
    
    	<?php
    	}
    }
    
    ?>
    Plugin Author Hector Cabrera

    (@hcabrera)

    And now, popular widget of my theme has the “freshness” filter you have on your plugin but if is possible, I need to add the default range too (no matter the date a post was published, you know).

    I’m not sure I understood what you meant with this. What are you trying to do?

    Thread Starter vicetias

    (@vicetias)

    Trying to modify that widget with the range data from your plugin (post-views-count is already with it) in especially this:

    <?php $popular_days_ago = "$popular_days days ago"; $recent = new WP_Query(array( 'posts_per_page' => $number, 'orderby' => 'meta_value_num', 'order' => 'DESC', 'meta_key' => 'post_views_count', 'date_query' => array( array( 'after' => $popular_days_ago )) )); while($recent->have_posts()) : $recent->the_post(); ?>

    It’s like the freshness of your plugin but I need the default way (time range)

    Plugin Author Hector Cabrera

    (@hcabrera)

    Ok, intentemos en espa?ol porque aún no estoy seguro de qué es lo que quieres hacer ??

    (For those who can’t speak spanish, I just asked the OP to explain things in spanish because I’m not following what’s he’s trying to achieve.)

    Thread Starter vicetias

    (@vicetias)

    Ok, así puedo explicarte mejor!

    Mira, lo que trato de decir es que quiero crear otro widget o modificar el que ya tiene mi tema. El código que te dejé más arriba es como el rango de tiempo “freshness” (en el que puedo elegir cualquier número de días para mostrar los posts populares) de tu plugin pero con otro código me imagino, entonces lo que necesito es a?adir la forma normal de tiempo de WPP, el que muestra por defecto los posts más populares sin importar la fecha en que fueron publicados!

    Estas dos opciones que incluye tu plugin necesito a?adir al archivo php.

    null

    No sé si funcione pero sé de algunos templates como bimber que incorporaron totalmente el plugin pero con nuevos archivos de widget, funciones, pero eso es muy complicado para mí, yo sólo necesito a?adirle la data de los rangos de tiempo del plugin.

    Lo de la función que te pedí está perfecta, está integrada y ahora cuenta las visitas desde tu plugin, por lo que post_views_count es vital para mi tema. Ahora solo me falta lo otro que espero hayas entendido. Gracias.

    • This reply was modified 7 years, 4 months ago by vicetias.
    • This reply was modified 7 years, 4 months ago by vicetias.
    • This reply was modified 7 years, 4 months ago by vicetias.
    Plugin Author Hector Cabrera

    (@hcabrera)

    Got it now, thanks ??

    To answer your question: porting WPP’s Time Range feature to another plugin / widget is possible (everything’s possible with the right mind and time), but it’s also represents a lot of work. So I have a question for you now: why reinvent the wheel? Why not just use the WPP widget (or any other widget out there) and save yourself some time? You probably have a very good reason to be doing all this, I’m just curious about it.

    Thread Starter vicetias

    (@vicetias)

    Bueno, pensándolo bien usaré ambos widgets por separado, en realidad es bastante complicado lo que quiero. Y respondiendo a tu pregunta era solamente para integrar completamente el plugin al template, pero lo que más quería era modificar la función de las visitas y ya está logrado gracias a tu ayuda.

    And now in english lol, thank you so much and keep it up this amazing plugin, it’s the best!

    Plugin Author Hector Cabrera

    (@hcabrera)

    Well, WPP can be fully integrated into any theme ?? (and for anyone reading this, here’s how.)

    Anyways, thank you for the kind words. I’m glad to know you like WPP ??

    Thread Starter vicetias

    (@vicetias)

    Acabo de percatarme de un problema con el contador. Tu plugin le pone un punto a los números cuando son miles, millones… y para que funcione esa meta key tiene que ser sin punto, por ejemplo: 1.015 debe ser 1015.

    ?Qué código debería a?adirle para quitarle los “.” a cada número?

    Plugin Author Hector Cabrera

    (@hcabrera)

    Ah, you’re right. Fortunately that’s an easy one to fix:

    Find:

    $count = wpp_get_views( $postID );

    Replace with:

    $count = wpp_get_views( $postID, 'all', false );

    Here’s the documentation, if you’re feeling curious: wpp_get_views().

    Thread Starter vicetias

    (@vicetias)

    I forgot to check that, now the number is ok, thank you!

Viewing 15 replies - 1 through 15 (of 15 total)
  • The topic ‘Post meta’ is closed to new replies.