I'm working on a wordpress, and using a plugin wordpress popular posts, and facing this issue.
How can I show a count of how many times a page has been viewed by visitors on category listing page or index page of the blog. This information is already there which is being used by plugin to display same in sidebar, not sure how can I use the same plugin data to show page view count on blog page.
I tried to find this, but didn't get exactly what I want.
Pls advise how to do this?
Plugin I use is http://wordpress.org/extend/plugins/wordpress-popular-posts/
You can simply do it without a plugin.
To count the post views, the first thing you have to do is to add the following code to your WordPress Theme functions.php
<?php
/*
* Set post views count using post meta//functions.php
*/
function customSetPostViews($postID) {
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $countKey);
add_post_meta($postID, $countKey, '1');
}else{
$count++;
update_post_meta($postID, $countKey, $count);
}
}
?>
And now we will call this function in the single.php to update the count value in the Database.
<?php
customSetPostViews(get_the_ID());//single.php
?>
Now in the same single.php file if we want to show the post view count, we can use this code:
<?php
$post_views_count = get_post_meta( get_the_ID(), 'post_views_count', true );
// Check if the custom field has a value.
if ( ! empty( $post_views_count ) ) {
echo $post_views_count;
}
?>
Now to show all the popular post in the descending order by post view count. use this code:
<?php//popular post query
query_posts('meta_key=post_views_count&posts_per_page=5&orderby=meta_value_num&
order=DESC');
if (have_posts()) : while (have_posts()) : the_post();
?>
<li><?php the_title(); ?></li>
<?php
endwhile; endif;
wp_reset_query();
?>
Happy Coding
There is a function called wpp_get_views provided by the plugin.
If you know the ID of the post/page for which you want to show the view count, all you need to do is to call the function with that ID as the parameter. For example:
$count = wpp_get_views($post->ID);
add_action('init','cr_tbl',55);
function cr_tbl(){
global $wpdb;
$table_add_two = $wpdb->prefix."post_view";
$cat_rating_ddl="
CREATE TABLE IF NOT EXISTS `".$table_add_two."` (
`pvid` INT(11) UNSIGNED AUTO_INCREMENT,
`ip` varchar(255) NOT NULL,
`device` varchar(255) NOT NULL,
`postid` int(11) NOT NULL,
`create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(pvid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
";
$all_tables = array();
$mytables=$wpdb->get_results("SHOW TABLES");
foreach ($mytables as $mytable){
foreach ($mytable as $t){
$all_tables[]=$t;
}
}
$sql_one='';
if(!in_array($table_add_two,$all_tables)){
$sql_one.=$cat_rating_ddl;
if(!empty($sql_one)){
if(!function_exists('wp_should_upgrade_global_tables')){
require(ABSPATH . 'wp-admin/includes/upgrade.php');
}
dbDelta($cat_rating_ddl);
}
}
}
function get_the_user_ip() {
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;}
function add_view_record($pid){
global $wpdb;
$ip = get_the_user_ip();
$device = (wp_is_mobile())?'mobile':'desktop';
$table_name = $wpdb->prefix.'post_view';
$list = $wpdb->get_results("SELECT * FROM $table_name WHERE postid = $pid and ip = '".$ip."'");
if(empty($list)){
$wpdb->insert($table_name,
array(
'ip' => $ip,
'device' => $device,
'postid' =>$pid,
)
);
}}
function get_view_count($pid){
$total=0;
global $wpdb;
$table_name = $wpdb->prefix.'post_view';
$list = $wpdb->get_results("SELECT count(pvid) as total FROM $table_name WHERE postid = ".$pid);
if(!empty($list)){
$total=$list[0]->total;
}
return $total;}
Related
I'm using "Search and filter" plugin, and "WP Favorites" plugin. I'm using following code in custom template
if ($query->have_posts())
{
while ($query->have_posts())
{
$query->the_post();
$meta_values = get_post_meta( get_the_ID() );
$post_meta_value = get_post_meta( get_the_ID(), '_audioigniter_tracks',true );
foreach($post_meta_value as $name) {
$kjkj = get_the_ID();
echo do_shortcode("[favorite_button post_id='$kjkj']");?>
<a class="a" href="<?php echo $name['track_url']?>"><?php the_title() ?></a><br/><?php
}
}
}
While in functions.php I'm using following code to sort but it's not working as I'm missing something related to user favorite posts meta
function myfunctions( $query, $sfid ) {
//global $wpdb, $query, $wp;
if($sfid==133203)
{
$favs = get_user_favorites();
foreach($post_meta_valuee as $fst) {
$query['order'] = 'DESC';
$query['orderby'] = 'meta_value';
$query['meta_key'] = 'simplefavorites_count';
}
return $query;
}
add_filter( 'sf_edit_query_args', 'myfunctions', 20, 2 );
Problem is in functions.php code, I'm somehow not able to let the query know info about users favorites (simplefavorites_count is total count by all users, not by current user). So I need help here.
I need to show only the primary category (a function added by default from YOAST) for a custom taxonomy in my template (wordpress).
The taxonomy is taken from the custom "course_category" in learnpress plugin.
It's a taxonomy that adds the categories into the courses created by the plugin.
I would like to create a function to call it in my loops, but i don't know how to write it properly for the custom taxonomies.
I found this code to use for standard categories (NOT FOR CUSTOM TAXONOMIES)
<?php
function get_primary_category( $post = 0 ) {
if ( ! $post ) {
$post = get_the_ID();
}
// SHOW YOAST PRIMARY CATEGORY, OR FIRST CATEGORY
$category = get_the_category( $post );
$primary_category = array();
// If post has a category assigned.
if ($category){
$category_display = '';
$category_slug = '';
$category_link = '';
$category_id = '';
if ( class_exists('WPSEO_Primary_Term') )
{
// Show the post's 'Primary' category, if this Yoast feature is available, & one is set
$wpseo_primary_term = new WPSEO_Primary_Term( 'category', get_the_id( $post ) );
$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
$term = get_term( $wpseo_primary_term );
if (is_wp_error($term)) {
// Default to first category (not Yoast) if an error is returned
$category_display = $category[0]->name;
$category_slug = $category[0]->slug;
$category_link = get_category_link( $category[0]->term_id );
$category_id = $category[0]->term_id;
} else {
// Yoast Primary category
$category_display = $term->name;
$category_slug = $term->slug;
$category_link = get_category_link( $term->term_id );
$category_id = $term->term_id;
}
}
else {
// Default, display the first category in WP's list of assigned categories
$category_display = $category[0]->name;
$category_slug = $category[0]->slug;
$category_link = get_category_link( $category[0]->term_id );
$category_id = $term->term_id;
}
$primary_category['url'] = $category_link;
$primary_category['slug'] = $category_slug;
$primary_category['title'] = $category_display;
$primary_category['id'] = $category_id;
}
return $primary_category;
}
?>
which i can call later with
<?php echo '<pre>'.print_r(get_primary_category(get_the_ID()), true).'</pre>'; ?>
I have used a Yoast seo plugin and set primary category for product. But in front I cannot get primary category name.
The Yoast SEO plugin now has a dedicated function — yoast_get_primary_term_id() — for getting the primary term's ID:
$primary_term_id = yoast_get_primary_term_id( 'taxonomy_slug', $post_id_or_object );
You can then use get_term() to get the WP_Term object:
// Will return `false` if no primary term has been set
$primary_term_id = yoast_get_primary_term_id( 'taxonomy_slug', $post_id_or_object );
if ( $primary_term_id ) {
/** #var WP_Term $primary_term */
$primary_term = get_term( $primary_term_id );
}
For those scenarios where you just need the term's name, you can use yoast_get_primary_term():
// Will return an empty string if no primary term has been set
$primary_term_name = yoast_get_primary_term( 'taxonomy_slug', $post_id_or_object );
Hi you can get using postmeta table.
$taxonomy = 'product_cat';
$primary_cat_id=get_post_meta($product->id,'_yoast_wpseo_primary_' . $taxonomy, true);
if($primary_cat_id){
$primary_cat = get_term($primary_cat_id, $taxonomy);
if(isset($primary_cat->name))
echo $primary_cat->name;
}
I could not get the accepted answer to work.
I modified this to fit my needs
$cat_name = ''; // I have this set in some shortcodes
if (!isset($cat_name) || $cat_name == '') {
if ( class_exists('WPSEO_Primary_Term') ) {
// Show the post's 'Primary' category, if this Yoast feature is available, & one is set. category can be replaced with custom terms
$wpseo_primary_term = new WPSEO_Primary_Term( 'category', get_the_id() );
$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
$term = get_term( $wpseo_primary_term );
if (is_wp_error($term)) {
$categories = get_the_terms(get_the_ID(), 'category');
$cat_name = $categories[0]->name;
} else {
$cat_name = $term->name;
}
} else {
$categories = get_the_terms(get_the_ID(), 'category');
$cat_name = $categories[0]->name;
}
}
echo $cat_name;
I have edited a working example to be more self contained, I used it for custom taxonomy so used get_the_terms() instead of get_the_category(). This code has not been tested in its current state.
I extended class WP_List_Table to display listing records of Custom Database Table. Listing is successful but I'm getting mad about how to implement a drop-down filter to filter my custom db table records according to its categories.
Please share any code to add drop-down filter to filter my custom database table records. Field name is cat_id.
after struggle of 3-hours after posting question here, i explored the class, and found the solution, so i am sharing information here.
There is a function function extra_tablenav( $which ), I override that function with my function,
function extra_tablenav( $which ) {
global $wpdb, $testiURL, $tablename, $tablet;
$move_on_url = '&cat-filter=';
if ( $which == "top" ){
?>
<div class="alignleft actions bulkactions">
<?php
$cats = $wpdb->get_results('select * from '.$tablename.' order by title asc', ARRAY_A);
if( $cats ){
?>
<select name="cat-filter" class="ewc-filter-cat">
<option value="">Filter by Category</option>
<?php
foreach( $cats as $cat ){
$selected = '';
if( $_GET['cat-filter'] == $cat['id'] ){
$selected = ' selected = "selected"';
}
$has_testis = false;
$chk_testis = $wpdb->get_row("select id from ".$tablet." where banner_id=".$cat['id'], ARRAY_A);
if( $chk_testis['id'] > 0 ){
?>
<option value="<?php echo $move_on_url . $cat['id']; ?>" <?php echo $selected; ?>><?php echo $cat['title']; ?></option>
<?php
}
}
?>
</select>
<?php
}
?>
</div>
<?php
}
if ( $which == "bottom" ){
//The code that goes after the table is there
}
}
and then I jumped into function prepare_items() and added a line after query string,
if( $_GET['cat-filter'] > 0 ){
$query = $query . ' where cat_id=' . $_GET['cat-filter'];
}
not finished here, I added some lines of javascript to execute drop down,
$('.ewc-filter-cat').live('change', function(){
var catFilter = $(this).val();
if( catFilter != '' ){
document.location.href = 'admin.php?page=ewc-testimonial'+catFilter;
}
});
and its working cool and fine, if anybody need more help then comment here.
Thank you for time.
I would like to display search results grouped by post type. I have regular posts, pages,
and a custom post type of product. How would I accomplish this by editing the below code.
The code below just shows all posts and pages right now.
<?php
while (have_posts()) : the_post();
echo "<h1>";
echo $post->post_type;
echo $post->post_title;
echo "</h1>";
endwhile;
?>
This code alters the original search query to order the results by post-type in the order you select. There are other solutions, but this is the only one i found that doesn't break pagination or requires multiple queries.
add_filter('posts_orderby', 'my_custom_orderby', 10, 2);
function my_custom_orderby($orderby_statement, $object) {
global $wpdb;
if (!is_search())
return $orderby_statement;
// Disable this filter for future queries (only use this filter for the main query in a search page)
remove_filter(current_filter(), __FUNCTION__);
$orderby_statement = "FIELD(".$wpdb - > prefix.
"posts.post_type, 'post-type-c', 'post-type-example-a', 'custom-post-type-b') ASC";
return $orderby_statement;
}
In your case, I'd do two things:
filter the search page's initial query to a particular post type
use one WP_Query call for each remaining post type
For (1), this would go in your functions.php:
<?php
function SearchFilter($query) {
if ($query->is_search && !is_admin()) {
if (isset($query->query["post_type"])) {
$query->set('post_type', $query->query["post_type"]);
} else {
$query->set('post_type', 'product');
}
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
?>
For (2), adapt the code you provided from your template file:
<?php
$s = isset($_GET["s"]) ? $_GET["s"] : "";
$posts = new WP_Query("s=$s&post_type=post");
if ( $posts->have_posts() ) :
while ( $posts->have_posts() ) : $posts->the_post();
echo "<h1>";
echo $post->post_type;
echo $post->post_title;
echo "</h1>";
endwhile;
wp_reset_postdata();
endif;
?>
You can re-use this code for each other post type.
It's best to avoid using query_posts... see querying posts without query_posts (even WordPress devs agree).
You need to alter the post query to reorder things. You would execute this just before you enter the loop. You can read more about query_posts in the Wordpress codex.
http://codex.wordpress.org/Function_Reference/query_posts
global $wp_query;
$args = array_merge( $wp_query->query, array( 'post_type' => array('type1', 'type2') ) );
query_posts( $args );
//the loop