How to create wordpress widget plugin, In this article, given full code and with explanation. For creating wordpress widget you just need use our code. In many wordpress themes we want to create the wordpress widget. For creating the wordpress widget you just need to put following code in functions.php file.
How to create wordpress widget plugin
This functions.php file you can find in wordpress theme folder.
01
class
My_Widget
extends
WP_Widget {
03
parent::WP_Widget(false,
'Our Test Widget'
);
05
function
form(
$instance
) {
08
function
update(
$new_instance
,
$old_instance
) {
12
function
widget(
$args
,
$instance
) {
16
register_widget(
'My_Widget'
);
this code
01
<!--?<span
class
=
"hiddenSpellError"
pre=
""
data-mce-bogus=
"1"
-->php
02
class
bm_widget_popularPosts
extends
WP_Widget {
04
function
bm_widget_popularPosts() {
05
parent::WP_Widget(false,
'Popular Posts'
);
08
function
widget(
$args
,
$instance
) {
09
$args
[
'title'
] =
$instance
[
'title'
];
10
bm_popularPosts(
$args
);
13
function
update(
$new_instance
,
$old_instance
) {
17
function
form(
$instance
) {
18
$title
= esc_attr(
$instance
[
'title'
]);
20
php
echo
$this
->get_field_id(
'title'
); ?>
"><!--?php _e('Title:'); ?--> <input id="
<?php
echo
$this
->get_field_id(
'title'
); ?>
" name="
<?php
echo
$this
->get_field_name(
'title'
); ?>
" type="
text
" value="
<?php
echo
$title
; ?>" />
22
<!--?<span
class
=
"hiddenSpellError"
pre=
""
data-mce-bogus=
"1"
-->php
25
function
bm_popularPosts(
$args
=
array
(),
$displayComments
= TRUE,
$interval
=
''
) {
32
FROM
' . $wpdb->posts . '
36
$request
.=
'post_date>DATE_SUB(NOW(), '
.
$interval
.
') '
;
39
$request
.= 'post_status=
"publish"
41
ORDER BY comment_count DESC LIMIT 0, ' .
$postCount
;
43
$posts
=
$wpdb
->get_results(
$request
);
45
if
(
count
(
$posts
) >= 1) {
47
if
(!isset(
$args
[
'title'
]) {
48
$args
[
'title'
] =
'Popular Posts'
;
51
foreach
(
$posts
as
$post
) {
52
wp_cache_add(
$post
->ID,
$post
,
'posts'
);
53
$popularPosts
[] =
array
(
54
'title'
=>
stripslashes
(
$post
->post_title),
55
'url'
=> get_permalink(
$post
->ID),
56
'comment_count'
=>
$post
->comment_count,
60
echo
$args
[
'before_widget'
] .
$args
[
'before_title'
] .
$args
[
'title'
] .
$args
[
'after_title'
];
64
<!--?<span
class
=
"hiddenSpellError"
pre=
""
data-mce-bogus=
"1"
-->php
65
foreach
(
$popularPosts
as
$post
) {
68
php
echo
$post
[
'url'
];?>"><!--?php
echo
$post
[
'title'
]; ?-->
69
<!--?<span
class
=
"hiddenSpellError"
pre=
""
data-mce-bogus=
"1"
-->php
70
if
(
$displayComments
) {
72
(<!--?<span
class
=
"hiddenSpellError"
pre=
""
data-mce-bogus=
"1"
-->php
echo
$post
[
'comment_count'
] .
' '
. __(
'comments'
, BM_THEMENAME); ?>)
73
<!--?<span
class
=
"hiddenSpellError"
pre=
""
data-mce-bogus=
"1"
-->php
77
<!--?<span
class
=
"hiddenSpellError"
pre=
""
data-mce-bogus=
"1"
-->php
83
echo
$args
[
'after_widget'
];
How to create wordpress widget plugin