INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Bulk delete WordPress posts with phpMyAdmin
I have over 8,000 posts generated by wp-o-matic and I want to get rid of all of them.
I want to execute this query in phpMyAdmin. I just want to make sure this is safe to run and it's not wiping out my pages. This is the query:
DELETE FROM 'wp_posts' WHERE 'post_type' = 'post'
Thanks | The join isn't that complex, but I wouldn't bother with it. Since you have a lot to remove a direct SQL query will run a LOT faster than WP.
However, we do need to keep track of the post ID numbers and remove the descendants and metadata.
Not tested / Make a backup / your risk etc. etc.
create temporary table `cull` (`post` int);
insert into cull select ID from wp_posts where my_criteria = 'my value';
delete from wp_posts where ID in ( select post from cull );
delete from wp_posts where post_parent in ( select post from cull );
-- done with temp table, cleanup metadata
delete from wp_postmeta where post_id not in ( select ID from wp_posts );
delete from wp_comments where comment_post_id not in ( select ID from wp_posts );
delete from wp_commentmeta where comment_id not in ( select comment_ID from wp_comments );
delete from wp_term_relationships where object_id not in ( select ID from wp_posts ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, bulk, phpmyadmin"
} |
How to display a term of taxonomy
My doubt is how can I show a "term” of an specific taxonomy, the problem is that I have not found an applying example, just short code lines that don’t show me nothing at all.
I want please the entire code to show the post.
My post type names: “sección_deportes"
My taxonomy names: “tipo_deporte”
and the term I want to show: “futbol”
I just found this: <
but the loop shows me the same posts repeatedly. | I found the solution thanks to answer this question: Specify number of posts in my 'tax_query'
I wanted to show the posts for 'futbol' within the 'tipo_deporte' taxonomy:
<?php
$args = array(
'posts_per_page' => 2,
'tax_query' => array(
array(
'taxonomy' => 'tipo_deporte',
'field' => 'slug',
'terms' => array('futbol'),
)
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
//The Post
}
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "taxonomy, terms"
} |
Include both default and Custom Post Type in query modified inside pre_get_posts
I want to include custom post type in the author arhive page. I tried the method discussed in this post:
> Including post_type = 'wiki' in author archives
add_action( 'pre_get_posts', 'custom_post_author_archive' );
function custom_post_author_archive( &$query )
{
if ( $query->is_author )
{
$query->set( 'post_type', 'custom_name' );
remove_action( 'pre_get_posts', 'custom_post_author_archive' ); // run once!
}
}
But by this method, only the custom_name posts are queried. I want to query both the custom_name posts and the normal posts.
What changes will I have to make? | As Kaiser mentioned, the `post_type` parameter can accept an array of post types. Updating the function to use `is_main_query()` to limit the filter to only the "main" query, the code would look like:
add_action( 'pre_get_posts', 'custom_post_author_archive' );
function custom_post_author_archive( $query )
{
if ( is_main_query() && is_author() )
{
set_query_var( 'post_type', array('post','custom_post') );
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, wp query, query"
} |
wpdb update add current timestamp not working
So using the $wpdb->update to add some data to a custom table, trying to add the current timestamp but it's not saving the right stuff(0000-00-00 00:00:00 this is saved).
overview code
$wpdb->update('mytable',
array(
'value' => 'hello world',
'edit' => date("Y-m-d h:i:s") //saves 0000-00-00 00:00:00
),
array(
'option_name' => 'the row'
),
array('%s, %s')
); | You seemed to have solved everything but the issue with the time:
> found the issue %d should be %s. but I see that it saves the server time not the current timezone
WordPress has a number of date/time related functions. In this case, it sounds like what you need is `current_time()`, which...
> Returns the blog's current local time in one of two formats, either MySQL's timestamp data type format (i.e. YYYY-MM-DD HH:MM:SS) or the Unix timestamp format (i.e. epoch).
So what you should need is:
$wpdb->update(
'mytable',
array(
'value' => 'hello world',
'edit' => current_time( 'mysql' )
),
array(
'option_name' => 'the row'
),
array('%s, %s')
); | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 11,
"tags": "database, wpdb, date"
} |
remove all submenus from plugin
Is there a way to un register all submenus at once instead of using the code below?
remove_submenu_page('myplugin', 'sub-page-1');
remove_submenu_page('myplugin', 'sub-page-2');
remove_submenu_page('myplugin', 'sub-page-3');
remove_submenu_page('myplugin', 'sub-page-4');
remove_submenu_page('myplugin', 'sub-page-5');
...
...
The idea is...
remove_submenu_page('myplugin', all);??? | Not without touching the global `$submenu` directly (which I wouldn't recommend - using only purposefully exposed APIs provides, in general, better stability).
However, if you wanted a function to remove all submenus:
/**
* Removes all submenus of given menu item
*
* @param string $menu_slug The slug of the parent menu to remove submenus of
*/
function wpse137406_remove_submenus( $menu_slug ) {
global $submenu;
if ( isset( $submenu[$menu_slug] ) ){
unset( $submenu[$menu_slug] );
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin development, admin"
} |
Pagination options using xml data instead of database?
Working on a custom plugin. I have an XML file containing over 500 items I need to make available for posting at the client's discretion. The client wants to share this plugin among a small group of peers, with no access to a central database, hence the XML file. We've done something similar in the past using data stored in a MySQL table and WP_List_Table for display and pagination, but I'm unsure about how to proceed using XML.
I'd prefer we create all posts as drafts that they can publish as desired, but for reasons I don't quite comprehend, that's not an option.
Basically, they want to see a list of all available items where they can simply click to publish individually or check multiple items and publish in bulk. Does that make sense? | No central database? Talk about not being able to see the forest for the trees. As long as the XML document is included with the plugin, I can just create a custom table and proceed as we have in the past. I do understand WP_List_Table is marked private, but I don't see anything wrong using it for a private plugin that will never make it to the repo. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pagination, xml"
} |
Get published posts and pages?
I'm working on a plugin to use gettext in posts and pages content.
I'm trying to get all published posts and pages in order scan them for translatable strings, but I cannot figure out how to do it.
This is what I'm trying:
$pages = $wpdb->query('SELECT * FROM wp_posts WHERE post_status = "publish"');
foreach ( $pages as $post ) {
print_r($post);
} | Don't use pure SQL if you don't have to. WordPress provides a useful and relatively solid class for retrieving post data. Use it.
$args = array(
'post_type' => array('post','page'),
'post_status' => 'publish',
'posts_per_page' => -1,
'ignore_sticky_posts' => true,
);
$qry = new WP_Query($args);
// Show post titles
foreach ($qry->posts as $p) {
echo $p->post_title;
}
Reference:
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wpdb"
} |
Pulling in content from another page
I'm using advanced custom fields and Im trying to pull content from sub pages onto the homepage
The below works but I was wondering whether it was possible to do this automatically and not write static ids on the fields?
<ul>
<li>
<?php the_field('content', 5); ?>
</li>
<li>
<?php the_field('content', 6); ?>
</li>
</ul>
The page setup is like:
home
-parent page
\--sub page
\--sub page
Any ideas would be much appreciated | Look into `get_children()`
<?php
$children = get_children( array( 'post_parent' => get_the_ID() ) );
if ( $children ) {
foreach( $children as $child ) { ?>
<li>
<?php the_field( 'content', $child->ID ); ?>
</li>
<?php } | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "advanced custom fields"
} |
'Trying to get property of non-object' when using WP_Query with 'fields' => 'ids'
In an attempt to speed up my query, I'm using the following arguments:
$args = array(
'post_type' => 'product',
'fields' => 'ids',
);
$query = new WP_Query($args);
While this does return an array of IDs as expected, I keep getting multiple `Trying to get property of non-object in /wp-includes/query.php` notices. This happens even when I have nothing inside my `while` other than `the_post()`:
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
endwhile;
endif;
Is `the_post()` causing this? Any idea why I'm getting these notices? | `the_post` places the next post object from `$query->posts` in the global `$post` and calls `setup_postdata`, which assumes `$post` is a post object, as it tries to access member vars of that object, which is where the errors come from.
In this case `$posts` is just an array of IDs instead of post objects. If you want to iterate over the results, you can do a `foreach` on `$posts`:
$args = array(
'post_type' => 'product',
'fields' => 'ids',
);
$query = new WP_Query($args);
if ($query->have_posts()):
foreach( $query->posts as $id ):
echo 'ID: ' . $id;
endforeach;
endif; | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 5,
"tags": "wp query"
} |
post_content with line breaks
I want to be able to get post_content with line breaks. What is the best way to do it?
I previously use the_content() which was working fine until I needed to install a plugin that adds share buttons on each post.
Since then the output of my the_content includes texts from the share buttons.
I tried to use post_contents which contains the correct content I need to output on my template file but the problem is the line breaks were stripped off.
Is it possible to get post_content with line breaks preserved?
Thanks | I believe this should work:
$getPost = get_the_content();
$postwithbreaks = wpautop( $getPost, true/false );
echo $postwithbreaks;
The second argument in wpautop can be up to you whether it's true of false, see the link below. It is described as follows:
> (bool) (Optional) If set, this will convert all remaining line breaks after paragraphing. Line breaks within <script>, <style>, and <svg> tags are not affected.
>
> Default value: true
Source: < | stackexchange-wordpress | {
"answer_score": 33,
"question_score": 10,
"tags": "the content, post content"
} |
Show Sitename on Yoast SEO Title tag
I am using Yoast SEO plugin on a site. Right now if a Post's Title is left empty in the metabox for a post, then the Title tag will output in this format...
%%title%% %%page%% %%sep%% %%sitename%%
Now if that same post does have a custom title text saved in it's meta field...then it shows only the text from the meta.
What I need to do is show `%%sitename%%` after the titlte text no matter what!
So even a title that is saved as `This is my title` the output on the HTML page will be...
`This is my title - SITENAME`
Does anyone know how to do this? | You can use the `wpseo_title` filter to read the tag for your site title after WPSEO creates it, and if it's not there, add it on.
add_filter( 'wpseo_title', 'wpse137502_wpseo_title' );
function wpse137502_wpseo_title( $title ) {
$site_title = get_bloginfo( 'name' );
if ( ! strpos( $title, $site_title ) ) {
$title .= " | " . $site_title;
}
return $title;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, title, seo, plugin wp seo yoast"
} |
show title if one of post meta exist
I have 4 metabox `facebook`, `twitter`, `instagram`, `youtube` with title "Follow Us". I am using this code to show facebook logo and link.
So if there are a value in facebook metabox I got the logo and the link.
Now my question, if One of this 4 metabox (facebook, twitter, instagram, youtube) has a value ( at least one of this 4 ), I need to show title "Follow Us on".
Thank you | I prefer below way,
$fb = get_post_meta($post->ID, 'ecpt_facebookpage', true);
$twitter = get_post_meta($post->ID, 'ecpt_facebookpage', true);
//etc...
if($fb != "" || $twitter != "" || $instagram = ""){
echo "Follow Us On";
if($fb != ""){ ?>
<a target="_blank" href=" echo $fb; ?>">
<img src="<?php bloginfo('template_url'); ?>/images2/service-fb.png" width="25px" height="33px" alt="" align="right">
</a>
<?php }
// And so on.....
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "metabox"
} |
Custom Login iframe doesn't work
I have a custom login window that I am building. The client requires a modal window for the login, so I have to use HTTP (for performance) for the regular page, and HTTPS for the login window (in the iframe for security), because of this, I get the error:
> Refused to display '< in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
I'm sure that this is a security feature so people can't iframe the `wp-login.php` page, but I want to remove it so this login will work properly. Is there anyway to remove the `'SAMEORIGIN' protection` for the `wp-login.php` page? | After doing some more research, I found this post: how can i embed wordpress backend in iframe. While the question it was asking didn't relate, the answer that toscho gave did. I'm reposting it here so it can be associated without click through:
> By default WordPress sends an HTTP header to prevent iframe embedding on /wp_admin/ and /wp-login.php:
>
> X-Frame-Options: SAMEORIGIN That's a security feature. If you want to remove this header remove the filters:
>
> `remove_action( 'login_init', 'send_frame_options_header' );`
> `remove_action( 'admin_init', 'send_frame_options_header' );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "login, wp login form, iframe"
} |
WP Plugin Running before jQuery
I'm having problems with jQuery and a plugin, the console error says jQuery is not defined. What I don't understand is it only fails when I load it to the production server, on my local dev installation it worked perfectly.
> ReferenceError: jQuery is not defined.
The plugin code:
add_filter( 'wp_footer', 'enqueue_footer_scripts', 9);
add_filter( 'wp', 'enqueue_styles', 11);
function enqueue_footer_scripts() {
wp_register_script( 'sjs', plugins_url('/js/sjs.js', __FILE__), array('jquery'));
wp_enqueue_script( 'sjs' );
echo "<script>jQuery(document).ready(function ($) { $('p').sJS();});</script>";
}
function enqueue_styles() {
wp_register_style('sjcss', plugins_url('/css/sjs.css', __FILE__), false, '2.1');
wp_enqueue_style('sjcss');
} | Your code doesn't work because of a fundamental ordering problem.
You're hooking into wp_footer. Then you're registering a script and enqueueing it. Finally, you echo some code.
Here's the problem, the act of enqueueing a script does not cause an echo of the script code immediately. Enqueueing does just what it says, it sets the script up to be added to the page output at a later time. So your echo of the script code here is too early.
Specifically, the enqueued scripts for the footer happen in the wp_print_footer_scripts call, which is connected to the wp_footer action with priority 20. So you need to enqueue before then, but print your custom script code after then.
So make a new function. Hook it to the wp_print_footer_scripts action. Then move your echo code into that, but leave the enqueue code where it is. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, theme development, jquery, wp enqueue script"
} |
Remove a plugin meta box from the dashboard
I'm trying to remove the meta box that the Download Manager plugin creates, as it uses a hardcoded http iframe, caused a mixed content error in ssl.
Here is the code that generates the meta box:
wp_add_dashboard_widget('wpdm_dashboard_widget', 'WordPress Download Manager', 'wpdm_dashboard_widget_function');
and here is the code I'm using in my theme's functions.php file:
function remove_dashboard_widgets(){
remove_meta_box('wpdm_dashboard_widget', 'dashboard', 'normal');
}
add_action('wp_dashboard_setup', 'remove_dashboard_widgets');
I also tried 'dashboard-network' as the 2nd parameter, as I'm running a multisite setup. Neither worked for me. Where am I going wrong? | I found that this works:
add_action('admin_init', 'rw_remove_dashboard_widgets');
function rw_remove_dashboard_widgets() {
remove_meta_box('wpdm_dashboard_widget', 'dashboard', 'normal');
}
I guess 'admin_init' is the key, so that it runs before the dashboard is loaded. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "metabox, dashboard"
} |
How to safely sanitize a textarea which takes full HTML input
I'm developing a plugin which enables the user to send HTML emails from within the WordPress admin. How should I sanitize the textarea input? It has to be able to contain the whole range of HTML tags that might appear in an HTML email. If I use `wp_kses()` then I would have to use a huge list of allowed tags.
The textarea saves its content to the db via custom options. | There is already a huge list built for you, which can be returned by `wp_kses_allowed_html()` based on context, and filtered via the `wp_kses_allowed_html` filter, also contextually. Creating that list should not be hard.
However, "the whole range of HTML tags that might appear in an HTML email" should be pretty close to the range allowed for an ordinary post so `wp_kses_post()` ought to get you a long way with little effort. | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 10,
"tags": "plugins, plugin development, sanitization"
} |
Hide a template part when page is password protected?
I'd like to hide the sidebar of my page when the page is password protected and the password has not yet been entered.
I've searched for a while and haven't found any condition I could use. Maybe `get_post_status` could help, but still, I wouldn't know when the user has entered the password and can see the full page. | You're after `post_password_required()`:
<?php if ( ! ( $post->post_password && post_password_required() ) ) get_sidebar() ?> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "conditional tags, private"
} |
Wordpress Background Audio - Continous AutoPlay
I'm kinda of a newbie , but know my way around a bit in Wordpress to code things in place.
I would like to know if you happen to know how to create a continous audio play in the background of the website , _including_ the time a visitor clicks on different pages, posts or sections of the website.
I have tried coding the audio into but that doesn't solve the problem because when the page reloads, the audio starts over and I don't want that.
Coding , plugins ... whatever does the job.
I know that this is not quite ok for the visitor , but please bear with me.
Thank you. | Since I don't have enough reputation to add a comment yet, I read on another website that someone used < as an alternative to frames/popups which seems to be a little script you can generate and then use on both non-WordPress and WordPress sites (since it just needs to be inserted after the `<body>` tag).
Or you can self-host the script (source) but either way, you should be aware that there are reported issues with SCM Player at the moment.
So without commenting on whether this script is a good or bad approach, how you apply it to your WordPress install will differ depending on your theme and if you prefer to self-host etc. But it will involve editing of theme files; whether this is your child theme or adding the relevant scripts to your theme's functions.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, audio"
} |
How to display Feedburner subscription count as plain text via a shortcode in post/page editor of my Wordpress blog?
I would like to create a shortcode like `[feedcount]` in my wordpress blog to display Feedburner subscription count as plain text on some of my posts/pages. Moreover, I'd prefer in the case that the Feedburner API is not unavailable, the shortcode shows "many other" instead of the count.
How can I do that? | As TomJNowell implies, you would achieve this by integrating the Feedburner API with the WordPress Shortcode API in a plugin. However, the Feedburner APIs have been shutdown since October 20, 2012 and this is no longer possible. As Google continues to deprecate support for Feedburner, your best course of action is to pursue alternatives to the service. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "shortcode, subscription, feedburner"
} |
How to display post title and link within wp_list_categories()
I'm testing something which needs to display posts within `wp_list_categories()`. Basically I want to display all content for a taxonomy.
I'm pretty sure that to make it happen I have to alter the WP class or function that handles categories and stuffs like this. Is that the way?
**EDIT:** I've opened the core file that contains `wp_list_categories()`. It's in `wp_includes` in the file called `category-template.php`
How can I alter this?
**EDIT 2:** there's a filter `wp_list_categories` | Off the top of my head, you can achieve the desired effect in two different ways.
## Extend the Category Walker
Extend the `Walker_Category()` class and overwrite the `start_el()` method with similar code that retrieves a list of posts in the category being processed and displays them in an unordered list within the category's `<li>` element. To use your new walker class, pass it's name in the `walker` argument of `wp_list_categories()`.
## Procedurally Process Cateogries
Rather than having `wp_list_categories()` echo out a list of categories, set the `echo` argument to `false`, set a variable to the function call's return value, and use the PHP regular expression and string functions to modify the markup as needed.
The second solution can alternately be achieved by hooking into the `wp_list_categories` filter, which receives the same generated markup as an argument that `wp_list_categories()` returns when `echo` is set to `false`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
About WP's save_post action
Quick question, in API's some times `save_post` is used(most of the time actually). Is `save_post` the equivalent of the query action `INSERT INTO` whereas `save_post` saves metadata and forces Wordpress to do the rest of the work when used correctly?
Thanks in advance! | Correct, "save_post" saves along with the meta_data which is stored in $_POST, $_GET or $post_data and then it is inserted into the posts table . let me know if that's helpful. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "query, save post, comparison"
} |
how to use $wpdb->prepare to update a custom table
As a noob I dont understand a lot of SQL injections but I need to be save so I have read that I have to use wpdb->prepare to make sure the data is stored correct.
At this moment I use the $wpdb->update() query so I need some help to transform this into an save query with $wpdb->prepare().
$wpdb->update('custom_table',
array(
'option_1' => 'hello',
'option_2' => 2,
'option_3' => 'world'
),
array('option_name' => 'some name'),
array('%s','d%','%s')
); | When you look at the Codex article on `$wpdb`, then you will see that your current usage is correct. The last argument
array( '%s', '%d', '%s' )
already indicates that there is something like `sprintf/printf` going on in the background.
The `$wpdb->prepare()` method isn't needed for every other method. The ones that need it:
$wpdb->query()
$wpdb->get_var()
$wpdb->get_col()
$wpdb->get_row()
$wpdb->get_results()
and plain SQL queries like:
$sqlQuery = $wpdb->prepare( "SELECT etc.", /* list of replacements */ );
_where the last probably will always get wrapped inside`$wpdb->query()` anyway._ | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wpdb, sql"
} |
get_posts() returns all posts rather than the ones specified with 'post_author' =>
I want to retrieve an array with the posts of a certain user for a custom post type category.
However, get_posts($arg) returns ALL posts of this custom post type, although I specified the post_author
<?php $pages = get_posts(array('post_type' => 'profile','post_author' => $post->post_author)); ?>
<?php var_dump ($pages); ?>
In this example $post->post_author is 11. However, the result of the code above is:
array(3) {
[0]=> object(WP_Post)#343 (24) {
["ID"]=> int(2326)
["post_author"]=> string(2) "11"
..etc.}
[1]=> object(WP_Post)#352 (24) {
["ID"]=> int(2324)
["post_author"]=> string(1) "0"
...etc.}
[2]=> object(WP_Post)#395 (24) {
["ID"]=> int(2322)
["post_author"]=> string(1) "0"
...etc.}
Why does get_posts() returns posts of authors whose ID is **not** 11? | `post_author` is not a valid parameter for `get_posts`. You really need to look at `WP_Query`'s argument list to see that, as `get_posts()` is really just a wrapper around that class.
> * **author** ( _int_ ) - use author id.
> * **author_name** ( _string_ ) - use 'user_nicename' (NOT name).
> * **author__in** ( _array_ ) - use author id (available with Version 3.7).
> * **author__not_in** ( _array_ ) - use author id (available with Version 3.7).
>
>
> <
What you want is `author` without the `post_` part. Try that, and it should work. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "get posts"
} |
Is it possible to get post metadata of referring page?
I'm trying to direct a php authorization script to act if the page that referred to it belongs to a certain category (free).
Is there something other than `<?php wp_get_referer() ?>` that will return more than the url? I basically need to get the id of the referrer. | `url_to_postid(wp_get_referer())` will give you the ID of the referring page/post if you were referred from a page or a post. It won't work if referred from some other types of pages, like archives.
You will then need to retrieve the categories for the ID to see if they match.
I would strongly consider passing a parameter with the request though. You should already have the post ID and possibly the post data on the referring page and won't have to make separate queries to grab it.
You can use a `nonce` to help prevent abuse of the parameter-- that is, to prevent someone from just typing `?status=free` into the URL.
You mention sessions in a comment. I have used sessions successfully in WordPress and with little trouble. Be aware that _a lot of people_ complain about sessions with WordPress.
See:
< | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "wp load.php"
} |
How can I whitelist only specific shortcodes for processing in text widgets?
I know that I can use the following filters to enable processing of shortcodes in Text Widgets:
add_filter( 'widget_text', 'shortcode_unautop');
add_filter( 'widget_text', 'do_shortcode');
How can I only whitelist a few specific shortcodes for processing, but not just process every shortcode? | add_filter( 'widget_text', 'wpse_137725_shortcode_whitelist' );
/**
* Apply only whitelisted shortcode to content.
*
* @link
*
* @param string $text
* @return string
*/
function wpse_137725_shortcode_whitelist( $text ) {
static $whitelist = array(
'gallery',
'form',
);
global $shortcode_tags;
// Store original copy of registered tags.
$_shortcode_tags = $shortcode_tags;
// Remove any tags not in whitelist.
foreach ( $shortcode_tags as $tag => $function ) {
if ( ! in_array( $tag, $whitelist ) )
unset( $shortcode_tags[ $tag ] );
}
// Apply shortcode.
$text = shortcode_unautop( $text );
$text = do_shortcode( $text );
// Restore tags.
$shortcode_tags = $_shortcode_tags;
return $text;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "widgets, shortcode"
} |
Remove empty lines ( ) when author updates their post
Whenever adding an empty line between paragraphs using TinyMCE, the ` ` character entity is added.
How can I strip the content of all instances of this character whenever an author updates their post (`save_post`)? | Figured it out, hooking into `content_save_pre`:
function remove_empty_lines( $content ){
// replace empty lines
$content = preg_replace("/ /", "", $content);
return $content;
}
add_action('content_save_pre', 'remove_empty_lines'); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "tinymce, the content, save post, characters, line breaks"
} |
single_term_title() running before get_the_title()
This is a strange "problem" but I've had this happen on a few installs and I was wondering if anybody could give an explanation on why / how this happens.
On a blog category if I code:
`<?php echo get_the_title(1).': '.single_term_title(); ?>`
Outputted to my screen: `UncategorizedBlog:`
On the otherhand, if I do this:
`<?php echo get_the_title(1); ?>: <?php single_term_title(); ?>`
I get the correct output `Blog: Uncategorized`.
I'm not sure if this is a PHP problem or a WordPress or maybe it's something in my code I've messed up along the way. Anyway I was curious as to why it appears that way since I would think order of operations would print the first function first, move onto the concatenation, then proceed to the `single_term_title()` but apparently this is not the case. | Try `<?php echo get_the_title(1).': '.single_term_title('', false); ?>`
From the Codex the second argument of single_term_title determines whether to "Display the title (TRUE), or return the title to be used in PHP (FALSE). Default: TRUE" | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "terms, blog, get the title"
} |
How to enable Zend Optimiser+ with Batcache
I am using Batcache with APC Object Cache Backend so far. A lot of posts on internet claiming that using Zend Optimizer instead of APC would reduce CPU and memory usage. I could enable Zend Optimizer on my server. But I haven't found a plugin or workaround to make Batcache works with Zend Optimizer.
Is that a "Zend Optimizer Object Cache Backend" for Batcache? How to make Batcache use Zend Optimizer?
Thank you. | Zend Optimizer+, or rather OPcache module as it is formally called included in PHP, is purely opcode cache. It doesn't implement key-value store and cannot be used as object cache back-end in WordPress. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, server, cache, apc"
} |
Logout and redirect using the WP Menu
I have a navigation hyperlink in my secondary menu, that will allow the user to logout:
!enter image description here
However, the user is prompted with the following screen for confirmation, when clicking on the hyperlink in the secondary navigation menu:
!enter image description here
I am currently using the following URL in the navigation menu to redirect the user back to the _Accounts_ page, as a temporary measure:
Is there a way that I can use the WordPress menu above, and place in an appropriate URL to log the user out without the confirmation screen, and then send them back to the page that they were previously on? | You have to hook into the wp_nav_menu_items filter to get the correct link with the nonce, as described here . An example of how to do that can be seen here < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php, functions, menus, redirect, navigation"
} |
Using a Taxonomy in Two Spots in a WordPress Post
I have a taxonomy called stocks. it has various items such as 'NFLX', 'AAPL', 'GOOG'
I want to be able to assign two things to a WordPress Post:
1. Main stock (only one item selected from the Stocks taxonomy.
2. Mentioned stocks (select one or more items from the Stocks taxonomy).
Here's the other thing, I want the slug for the MAIN STOCK to be in the URL of my post.
Example:
I write an article on Apple Inc and mention other competing companies. The main stock would be AAPL. Mentioned stocks would be AAPL, GOOG, AMZN, etc. And I'd want the URL to be `www.example.com/AAPL/the-name-of-the-article`
So, I'm trying to avoid creating two taxonomies (i.e. Main Stock and Mentioned Stocks) and filling both up with the same set of stocks. Ideally, I want to create one taxonomy and use it in two places. Then pull the slug for that taxonomy item selected for the "main stock" to be used in the URL of the post itself.
Is this possible? | You can do this by using the category taxonomy for your stock symbols, then in permalink settings you would select the custom permalink structure with /%category%/ to get your url of AAPL/article-title.. Then you could use tags for mentioned stocks so you can tag the article with AAPL, GOOG, etc.. You don't even need to setup a custom taxonomy. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, taxonomy"
} |
How to move plugin link from left navigation to a different location?
I have the Advanced Custom Fields plugin. How do I move the link so it's under Settings (like some other plugins) or under the Screen Options Tab? I don't want to hide it completely as I would still need to be able to use it. Is this possible and if so how do I do it? | There is a very popular plugin that gives you this ability in an easy package
Admin Menu Editor | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "dashboard, admin menu"
} |
jQuery does not appear to be enqueued on static homepage
I have been searching why, but I am clueless, I cannot figure out what is happening... jQuery does not appear to be enqueued on static homepage (I am not used to work with static homepages).
On regular pages (and blog), `wp_head()` loads javascript files, css and stuff. On static homepage, it loads everything **except** javascript files (none at all), including my dear jQuery...
I just begun working on the theme, so I don't get it... It is based on a Twenty Twelve theme, so the code did not change much yet. I just touched `footer.php` and `style.css`, and I inverted sidebar & primary blocs on `index.php` and `page.php` (I am styling the sidebar horizontaly above the primary content).
If anyone has an idea, I would be glad to get some help ! | If you need it everywhere, simply enqueue it from your functions.php. See the codex for ore details
function wpa_137833_scripts() {
wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'wpa_137833_scripts' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, wp enqueue script, wp head"
} |
wpdb prepare: passing varible number of fields as second argument
As i want to manage the NULL fields in my db and wordpress functions doesn't allow to do so, i will need to dynamically generate a query depending on the situation. The problem is that i don't know how to pass a variable number of fields as second argument! this is what i've been tr but it returns an "Empty query" error:
if ($a == '') {
$fields = 'b, c';
$placeholders = "'%s', '%s'";
$vars = $b . ', ' . c;
} else {
$fields = 'a, b, c';
$placeholders = "'%s', '%s', '%s'";
$vars = $a . ', ' .$b . ', ' . c;
}
global $wpdb;
$wpdb->show_errors();
$query = 'INSERT INTO table (' . $fields . ') VALUES (' . $placeholders . ')';
$wpdb->query($wpdb->prepare($query, $vars));
is there any way to do so (even using $wpdb->insert)? | You must use an array for your `$vars`, so replace
$vars = $a . ', ' .$b . ', ' . c;
with
$vars = array( $a, $b, $c );
But I would rather recommend you to use the `$wpdb->insert( $table, $data, $format )` method. Then your code example could look like this:
$data = array( 'a' => $a, 'b' => $b, 'c' => $c );
$format = array( '%s', '%s', '%s' );
if( empty( $a ) )
{
$data = array_slice( $data, 1, 2 );
$format = array_slice( $format, 1, 2 );
}
$wpdb->insert( $table, $data, $format ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "wpdb"
} |
Executing query_posts after wp_insert_post
am working on a custom plugin. I'm programmatically adding a new post in the plugin use `wp_insert_post`. Works fine, the post gets added and I get the `$post_id`. However, if I immediately run `query_posts` and try and reset the $wp_query to point to the new post_id I get nothing.
I feel I am not using `query_posts` correctly ... because I would think it should return the new post.
<?php
wp_reset_query();
$args = array(
'post_title' => 'test post',
'post_author' => 1,
'post_status' => 'publish',
);
$post_id = wp_insert_post( $args );
if ( $post_id != 0) {
query_posts( array( 'post_id' => $post_id ) );
} | I don't think `post_id` is a valid query argument - use `p` instead. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query"
} |
Show all wp_get_post_terms slugs
I am using the following code to display my custom taxonomy slugs. However it is only displaying the first category and not all the related categories. I know this is fairly simple and is to do with [0] but I can't figure out how to change it.
$getslugid = wp_get_post_terms( $post->ID, 'opd_taggallery' );
$getslug = $getslugid [0]->slug;
echo $getslug; | This is more of a PHP question, but the solution is simple - you need to use a `foreach`-loop on `$getslug`, because you just echo the slug of the first taxonomy.
The function `wp_get_post_terms()` does not return a single object, but an array of objects. You are right with the `[0]`, this indicates that you are checking the first entry of said array.
Your function should look something like this:
$getslugid = wp_get_post_terms( $post->ID, 'opd_taggallery' );
foreach( $getslugid as $thisslug ) {
echo $thisslug->slug . ' '; // Added a space between the slugs with . ' '
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "slug, terms"
} |
Default Display Name As Username
I don't know why it's so hard to find a solution for this but nothing seems to work when i finally find an answer..
I want to simply make the default display name as the users login/username..
I know I can edit each user, but I want it to be set like that for everyone and everyone that registers in the future.
Any ideas?
Thanks | /**
* Set new user's display name as their login.
*
* @link
*
* @param int $user_id
*/
function wpse_138034_display_name_as_login( $user_id ) {
if ( $user = get_user_by( 'id', $user_id ) ) {
// Prevent infinite loop.
remove_action( 'user_register', __function__ );
wp_update_user(
array(
'ID' => $user_id,
'display_name' => $user->user_login,
)
);
// All done, restore.
add_action( 'user_register', __function__ );
}
}
add_action( 'user_register', 'wpse_138034_display_name_as_login' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "customization, username"
} |
How do I enqueue a js file in functions.php for a if lt IE 9 statement?
I'm coding a theme that uses the Twitter Bootstrap 3 files and in the header I want to include:
<!--[if lt IE 9]>
<script src="<?php echo get_stylesheet_directory_uri(); ?>/js/html5shiv.js"></script>
<script src="<?php echo get_stylesheet_directory_uri(); ?>/js/respond.min.js"></script>
<![endif]-->
I've been told by a theme reviewer that I can't put it in the header file (only one js is allowed).
> Required: Theme can include only one JS within header.php, please enqueue the additional > respond.min.js using the hook wp_enqueue_scripts in functions.php
as it is I have to enqueue it, but I don't know how to do this in a way that put's it in the "if it IE 9" statement.
Please could someone help me? Thanks | You can do it in two ways....
Solution One:
<?php
add_action( 'wp_head', 'myscript' );
function myscript(){
echo '<!--[if lt IE 9]><script src="your_js_file_path"></script><![endif]-->';
};
?>
Solution Two:
<?php
global $wp_scripts;
wp_register_script( 'jsFileIdentifier', 'YourJsFilePath', array(), '3.6.2' );
$wp_scripts->add_data( 'jsFileIdentifier', 'conditional', 'lt IE 9' );
?> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "wp enqueue script, twitter bootstrap"
} |
Can't insert caption into image
You can see live example here. When I add a caption into the image, it doesn't show at all!
I've added the caption to the image as you can see in the next picture
!Here
but it doesn't show as you see below
!here
But when I click edit the picture icon as you see below
!here
and fill in the caption field
!here
the caption works!
!fine
Why it's not working in the first case? I've disabled all plugins and no luck! I've tried the twenty fourteen theme, and no problem there, so the problem is in my theme only. Can you please help! | I solved it, the problem was a function I used to use and forgot about!
add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 );
add_filter( 'image_send_to_editor', 'remove_thumbnail_dimensions', 10 );
function remove_thumbnail_dimensions( $html ) {
$html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
return $html;
}
I removed this function and everything is OK now. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "captions"
} |
Plugin problem. Question is not appearing.
I have installed a plugin DW Q & A and I have posted some questions on it too. But when I click on the questions it is not available. why?
The questions on the page: !enter image description here
after clicking on a question !enter image description here
**What is need to set up to view the questions?** | From plugin's page FAQ:
> If your updating makes your site inaccessible and your posts, questions return a 404 Error page, don’t panic, all your posts are still there and safe. What you need to do is fix the permalink settings of the DW Question & Answer plugin.
Make sure you are following instructions from "Permalink Settings". | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins"
} |
Custom Content Type with No Page View
I am trying to define a custom content type, more exactly I want to create some controls in a content type for a slider that I will show on the home page custom template.
What I would like to know if it's possible to make the content type to don't have a view (a actual page where it would show up). | When register your CPT, to make the content type don't have a view, you cant set `publicly_queryable` to `false`. According to the Codex, "If you set this to FALSE, you will find that you cannot preview/see your custom post (return 404)." | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, customization"
} |
How To Get Posts With A Specific Word
How to retrieve posts with a specific word in the loop. For example, I want to retrieve all posts with the title of the profile post (custom post type): <
I created profiles in my website, and I want to display all the posts which contains the word "Dolph Ziggler" or the name of the profile. | What you've described is just a search for the words "Dolph Ziggler".
You can use WP_Query as such
$query = new WP_Query( 's=keyword' );
Note, that you'll probably want to cache those queries as they'll be very slow. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, loop, query posts"
} |
SELECT from wp_users, get Displayname too
SELECT post_author, count(ID) as amount
FROM dbold_posts
WHERE WEEKOFYEAR( post_date ) = WEEKOFYEAR( NOW() )
AND post_status = 'publish'
AND post_type = 'post'
GROUP BY post_author
I can't figure out how I'll get the Display name, instead of "post_author" in this query. It fetches the info as I want it - I just want the displayname instead of the authors ID.
Any ideas? | You will need to do a `JOIN` on the users table in your old database, and also select the display name.
One key thing to note here, is that I aliased `dbold_posts` as `P`, and `dbold_users` as `U` \- when dealing with multiple table, it's always best practice to specify which table you are referring to when mentioning a column.
SELECT P.post_author, count(P.ID) as amount, U.display_name
FROM dbold_posts P
JOIN dbold_users U on U.ID=P.post_author
WHERE WEEKOFYEAR( P.post_date ) = WEEKOFYEAR( NOW() )
AND P.post_status = 'publish'
AND P.post_type = 'post'
GROUP BY P.post_author | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, user meta, sql"
} |
How can I check if the admin bar is visible to the current user?
I'm new to WordPress. I would like to know
* Is the admin bar visible to all users and roles?
* If not, how can I check it is visible to the current user? | Just use `is_admin_bar_showing()` to check if the _currently logged in user_ is
1. logged in
2. has activated the admin bar in his user settings/preferences | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "users, user roles, admin bar"
} |
Admin - no Featured image choice in create new/page|post
I am developing a WP theme and I wanted to add a thumbnail/featured image to a new page/post but there is no such option/choice - like it used to be, I am using WP 3.8.1, I did try to turn off all the plugins - didnt help, I also checked the console for any errors - no error.
Interesting is that with the native "Twentyfourteen" theme it works/shows.
Any idea what might cause this behaviour? Is there anywhere anything what could turn this off? | Your theme has not registered support for post thumbnails. You need to add one of these as appropriate:
add_theme_support( 'post-thumbnails' );
add_theme_support( 'post-thumbnails', array( 'post' ) ); // Posts only
add_theme_support( 'post-thumbnails', array( 'page' ) ); // Pages only
add_theme_support( 'post-thumbnails', array( 'post', 'movie' ) ); // Posts and Movies
See the Codex (link above) for more information. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, theme development, pages, post thumbnails, thumbnails"
} |
Enqueue Wordpress jQuery after it's been deregistered by a plugin
I'm looking after a Wordpress install that makes use of a plugin that deregisters jQuery and replaces it with it's own ancient version. I'm aware of why loading your own jQuery is irresponsible and would like to use the version of jQuery bundled with Wordpress. I'm currently deregistering the plugin's version of jQuery and enqueuing the Wordpress version. However my approach makes some assumptions about the location and version of jQuery. Is there a better way to do this and ensure things don't break when Wordpress is updated?
wp_deregister_script( 'jquery' );
wp_enqueue_script( 'jquery', '/wp-includes/js/jquery/jquery.js', array(), '1.10.2', false ); | I think you can just use:
wp_enqueue_script( 'jquery' );
And WordPress will know to use the included one.
**Edit:**
You can use:
wp_enqueue_script( 'jquery-core' );
Assuming that hasn't also been deregistered by another script. I guess this could run the risk of allowing a plugin to register 'jquery' and for 2 versions of jquery to be loaded, though. Keep an eye out! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, wp enqueue script"
} |
Adding pretty query parameters
A custom post type named shooting has a field (with ACF) with plenty of images. Those are listed on the `single.php` of the CPT and one of those images is displayed in full-ish size. I currently have URLs like `shooting/foo-bar/?image=1` where 1 is the index (not ID) of the image that should be displayed large.
Is there a way to get prettier URLs like `shooting/foo-bar/1` with WordPress? Or would I have to write a custom rewrite-rule for that? | You would need a custom rewrite rule for that:
<
I think you might have a hard time though, with it being within an area of the site (single post type) already using a custom rewrite rule! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "url rewriting, urls"
} |
Can i have more than one form for front end posting in one template
I'm building a front end post form for car dealing. I have the "if statement validation" at the begining of my template, before get_header() function, after that i have the form. Can i have two or more forms in that template without a conflict? | Yes. You can check which form is being submitted by adding a "name" attribute to the submit button.
<input type="submit" name="form1" value="Submit">
Then in you validation, just check if that exists:
if(isset($_REQUEST['form1'])){
// Form 1
} elseif(isset($_REQUEST['form2'])) {
// Form 2
}
This is one method at least, there are plenty of ways to deal with it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, front end"
} |
WP Business Directory Manager Plugin Admin Listings?
I'm using the WP Business Directory Manager plugin and I'm having some problems. I've been meaning, as an admin, to add a Listing to my directory, but it shows pended, so i look a round the plugin a found a way to change it in the backoffice but it published every listings. Is there a way to have only the admin that his listings get published by default?
In the `listing.php`:
if ( !$data->listing_id && ( !$listing_cost || current_user_can( 'administrator' ) ) ) {
wp_update_post( array( 'ID' => $listing_id, 'post_status' => wpbdp_get_option( 'new- post-status' ) ) );
}
the setting of the `new-post-status`:
$this->add_setting($s, 'new-post-status', _x('Default new post status', 'admin settings', 'WPBDM'), 'choice', 'pending', '',
array('choices' => array('publish', 'pending'))
);
Much appreciated. | You can test by the admin login name:
$current_user = wp_get_current_user();
$my_user = $current_user->user_login;
if (strpos($my_user,'admin') !== false) { // test for the admin username
if ( !$data->listing_id && ( !$listing_cost || current_user_can( 'administrator' ) ) ) {
wp_update_post( array( 'ID' => $listing_id, 'post_status' => 'publish' ) ); //update post to publish
}
}else{
if ( !$data->listing_id && ( !$listing_cost || current_user_can( 'administrator' ) ) ) {
wp_update_post( array( 'ID' => $listing_id, 'post_status' => wpbdp_get_option( 'new-post-status' ) ) ); //let the post in "pendin" position
}
}
Hope this would workout for you. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php"
} |
Including all terms in wordpress tax_query
I'm a little bit confused, why I can't include all the terms in tax_query automatically?
**My code:**
'tax_query' => array(
array(
'taxonomy' => 'city',
'field' => 'slug',
'terms' => array( nyc, boston, london ),
)
)
What If I've dozens of cities? Isn't it uncool to add them all manually? | Unless you have posts that _don't_ have a city aren't you essentially querying all your posts? Anyway, Eric Holmes is correct that you should be using `WP_Query` in lieu of `query_posts()`.
That said, you can get a list of all the terms in a taxonomy and then use those values in your tax query.
// get all terms in the taxonomy
$terms = get_terms( 'city' );
// convert array of term objects to array of term IDs
$term_ids = wp_list_pluck( $terms, 'term_id' );
// proceed with tax query
$args = array ('tax_query' => array(
array(
'taxonomy' => 'city',
'field' => 'term_id',
'terms' => $term_ids,
)
)
);
$city_posts = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 5,
"tags": "custom taxonomy, wp query, loop, tax query"
} |
add javascript files only when plugin is called?
I'm writing a WP plugin that might be called on any page using a simple function call:`getDeck(Deck_id)` \- and i'd like to add my javascript files on pages where this function is called ONLY, as opposed to having it on every page...
What do I do? | If your scripts can be printed in the footer add the enqueue to the definition of `getDeck`, with the final argument set to `true`.
I.e in your plugin file
function getDeck( $deckId )
{
wp_enqueue_script( $handle, $src, $deps, $ver, true );
//do other stuff
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, javascript"
} |
Comments from other blogs are getting added to my blog?
Today I started receiving a ton of requests to moderate comments on my blog, but when I looked at the comments they are clearly from multiple other people's blogs. What could be the cause of this and what do I do about this? | Those are pingback or trackbacks. They are mechanisms by which blogs alert each other about cross-linking or references to other posts.
Pingbacks and trackbacks are common from SPAM or scrapper sites so you do want to take a look and make sure you are not approving comments from disreputable sources but in general, these are normal and can be useful.
The pingback/trackback functionality has been built into WordPress for as long as I can remember. Your site probably sends similar "comments" to other blogs. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments"
} |
Fatal error after changes to functions.php, even with original file
Getting `Fatal Error: Cannot redeclare theme_feature_setup()` message after code changing in the functions.php file. I've tried deleting functions.php file and uploading the previous version but I still get the same error message.
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
included in config.php file.
Also NO error.log file is created in wp-content.
ERROR MESSAGE:
Cannot redeclare bean_feature_setup() (previously declared in htdocs/wp-content/themes/koi-child/functions.php:33) in htdocs/wp-content/themes/koi/functions.php on line 33
How should I proceed? | Ok, removed my first answer, that is why it is important to give as much info in your question as possible. You cannot copy functions from your parent theme to your child theme. You also cannot coipy the parent themes functions.php to your child theme
The only time you can keep the same function name between parent and child theme is when the parent theme is enclosed in a `if (function exist()` hook. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, debug, fatal error"
} |
Question on WooCommerce Syntax
The Below syntax removes the "Related products" from appearing on the Single Product page, but what does the 20 stand for ?
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20);
Thanks. | 20 is the priority. To remove, must use the same priority as the one that was set in the add_action. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Default value for add_settings_field
I'm creating a simple settings page by following these instructions.
Since this is a custom plugin, I'd like one of my settings to start with a predefined value (that can later be changed). What is the recommended way to set a default value for a setting added with `add_settings_field`? | if ( get_option( 'my_setting' ) === false ) // Nothing yet saved
update_option( 'my_setting', 'default_stuff' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 7,
"tags": "customization, settings api"
} |
How to stop PHP code running when in a child theme
I understand you can add extra CSS on top of the parent theme, but how do you remove PHP code from functions.php?
I want to remove the `Masonry plugin` in `twentyfourteen` theme, and have located the piece of code on `line 254`.
if ( is_active_sidebar( 'sidebar-3' ) ) {
wp_enqueue_script( 'jquery-masonry' );
}
If I'm editing the parent theme, I can just comment this block out `/* */`.
But I'm not aware of a way to change this is my child theme. | You can't actually "remove" PHP code from the parent theme. What you can do is undo things done there.
The counterpart of `wp_enqueue_script` is `wp_dequeue_script`.
If you put this in your `functions.php` it should remove the `Masonry Plugin` (untested)
add_action( 'wp_print_scripts', 'de_script', 100 );
function de_script() {
wp_dequeue_script( 'jquery-masonry' );
}
Source: Function Reference/wp dequeue script @ Codex
As I haven't tested this be aware of the fact that this could have unwanted side effects if the theme relies on the `Masonry Plugin`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "php, child theme, masonry"
} |
Change media attachment author via mysql query
How does one bulk change the media attachment author via an sql query?
I have hundreds of media attachments that need to be moved to another author so the original author can be deleted; but that author has no posts, only media attachments.
(The images were attributed to the author when importing and running a query to take the first post image and make it a featured image.)
I think I need to specify the `post_type' in a query, like this:
`update wp_posts and post_type = ‘attachment’`
**Update:**
As answered below, this works `UPDATE wp_posts SET post_author = [NEW_ID] WHERE post_author = [OLD_ID]`
with or without the `AND post_type = 'attachment'` | UPDATE wp_posts SET post_author = [NEW_ID] WHERE post_author = [OLD_ID] | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "query, author, media"
} |
Wordpress constantly running out of memory
My Wordpress installation on a shared hoster is constantly running out of memory:
The error pops up at seemingly random, for example when uploading photos or sometimes without doing anything just browsing the Admin area.
It is a very fresh installation (with little content and traffic), I receive this error no matter which Theme and which plugins I use.
I already added these lines to my config:
.htaccess
php_value memory_limit 128M
wp_config.php
define('WP_MEMORY_LIMIT', '128M');
define( 'WP_MAX_MEMORY_LIMIT', '256M' );
My PHP Limit seems sufficient:
PHP Memory Limit:
memory_limit 512M 512M
HOWEVER after all this my memory monitor plugin still says:
WordPress Memory Limit: 40M
Do I have to do anything else to apply these changes? | Try
`memory_limit = 128M`
in php.ini. Your syntax may be wrong.
You can run a function called phpinfo to see what kind of memory allocation you really have. Make a plain text file and call it `phpinfo.php` and put just this line in it:
`<?php phpinfo(); ?>`
then put the file in the root of your server, and then go to that file with your web browser, i.e. mydomain.com/phpinfo.php
You'l see all the php info you need; scroll down for memory settings. If you get an error, that means your web hosting company won't allow phpinfo to run for security reasons.
But that will tell you what the real memory settings are and if your host is being honest. If they are, ask them how to bump memory for your account. If you only see a memory limit of 40 megs, than you're not able to change it due to their restrictions. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "htaccess, wp config, memory"
} |
how to get db values without using an loop with wpdb->get_results()
So I want to return the data from 1 row from my custom DB table, but I dont want to use a loop as I only need the values once....so is there a way to do this?
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM mytable WHERE the_id = %d", $id));
$results->the_id;//not working
$results->the_name;//not working
... | You want `get_row`. Per the Codex:
> Get all the information about Link 10.
>
>
> $mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10");
>
>
> The properties of the $mylink object are the column names of the result from the SQL query (in this example all the columns from the $wpdb->links table, but you could also query for specific columns only).
>
>
> echo $mylink->link_id; // prints "10"
>
>
> < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wpdb"
} |
Redirect not logged in users if they are on a specific page
I've seen this question posted before but not exactly trying to achieve what I want.
Basically what I want is: If user is not logged in AND is on -this page- OR -this page- OR -this page, redirect him to -this page- (which is a custom registration page)
I'm tweaking this piece of code, but it's not working. I'll appreciate any type of guidance.
<?php
function redirect_non_logged_in(){
// if user is not logged and is on this pages
if( !is_user_logged_in() && is_page( array( 250, 253 ) ) {
//This redirects to the custom login page.
wp_redirect(site_url('/user-registration'));
exit();
}
}
add_filter('get_header','redirect_non_logged_in');
?> | Your function is fine, but `'get_header'` it's too late.
Use `template_redirect` instead:
add_action( 'template_redirect', function() {
if ( is_user_logged_in() || ! is_page() ) return;
$restricted = array( 250, 253 ); // all your restricted pages
if ( in_array( get_queried_object_id(), $restricted ) ) {
wp_redirect( site_url( '/user-registration' ) );
exit();
}
});
Be sure to not include 'user-registration' page id in `$restricted` array or you'll experience an endless redirect... | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "redirect"
} |
How to check if single.php has already called the_post_thumbnail function
I am creating a front end plugin to upload images and adding filter in `the_content()` to display post thumbnail but some templates already have `the_post_thumbnail` in `single.php` or `loop.php`. Is there any way I can check it? | There are several hooks in `get_the_post_thumbnail` for example
* `begin_fetch_post_thumbnail_html`
* `end_fetch_post_thumbnail_html`
`/wp-includes/post-thumbnail-template.php`
You could add a function to one of these actions which removes your filter on first run.
If you need further help with this please add some code how you filter `the_content`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "posts, post thumbnails, actions, the content"
} |
if (is_page(**PAGE ID**)) not working
I'm following this tutorial on adding Google Content Experiments code to `header.php`.
I added the following code to `header.php`:
<?php if (is_page('346') ):?>
<!-- Google Analytics Content Experiment code -->
...
<!-- End of Google Analytics Content Experiment code -->
<?php endif; ?>
This didn't produce the content experiment code on the front end. I tried:
<?php if (is_page(346) ):?>
<!-- Google Analytics Content Experiment code -->
...
<!-- End of Google Analytics Content Experiment code -->
<?php endif; ?>
This didn't work either.
Can you see why this code is not working? Thanks. | you can use this for
<?php
global $post;
if( $post->ID == 346) { ?>
<!-- do your stuff here -->
<?php } ?>
you can use this anywhere either in header or anywhere else. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 7,
"tags": "conditional tags"
} |
Obtaining the original unchanged Theme
Quite a few months back, I had used a third party theme v 2.9 in my wordpress site. I made a few custom changes to css/.php based on my needs. Now, I plan to upgrade the theme to v3.8.
Before doing that, I wanted to get the diff of changes that I had made to ver 2.9. As I didn't have a copy of the original theme, I contacted the developers of the theme; unfortunately, they also don't seem to have a copy of that.
What are my options to obtain the diff, get an original copy of the theme? Does wp store a copy of original theme somewhere? My site is hosted on bluehost.
Thank You. | WordPress doesn't store a copy of themes.
I see several options:
* Find out why the creator of the theme doesn't have a copy of the theme at version 2.9. It is really weird that any serious developer wouldn't keep a copy of old versions.
* Check your own backups.
* Ask your hosting provider if he has backups.
* How did you get the theme in the first place? Maybe you still have a copy in your Downloads folder or Mail Inbox? | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -3,
"tags": "themes, child theme"
} |
"No Data Received" error in Chrome every time i try to update the theme functions file
Under Appearance --> Editor --> functions.php ( Theme functions ), whenever i try to modify a piece of code in it and click Update, i get this "No Data Received" error in Chrome. I never get this error when i click on any other area in WordPress or theme options, custom css etc.
I don't know why i am getting this error. I use GoDaddy hosting. Can someone please help me out on this issue.
Thanks ! | I contacted GoDaddy support and they advised me to login to the hosting manager and make the edits to the functions.php file from there. That way it worked !
Though i still couldn't figure out why i was getting that problem when i tried to edit it from within my WordPress dashboard, but anyways the problem is solved now.
Thank you @ialocin and @s_ha_dum for your help ! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes, theme options, theme customizer"
} |
Getting Plugin directory and url
In one of my theme the path and directory is set by
if( !defined('ADMIN_PATH') )
define( 'ADMIN_PATH', get_template_directory() . '/admin/' );
if( !defined('ADMIN_DIR') )
define( 'ADMIN_DIR', get_template_directory_uri() . '/admin/' );
If I want to convert it into plugin what will be the correct way?I have tried plugins_url(), plugin_dir_url() but those didn't work. | Use the `plugin_dir_path()` and `plugin_dir_url()` helper functions:
if( ! defined( 'MY_PLUGIN_PATH' ) )
define( 'MY_PLUGIN_PATH', plugin_dir_path( __file__ ) . 'admin/' );
if( ! defined( 'MY_PLUGIN_DIR' ) )
define( 'MY_PLUGIN_DIR', plugin_dir_url( __file__ ) . 'admin/' );
You should be using more unique constant names - `ADMIN_PATH` is far too generic. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -2,
"tags": "plugin development"
} |
Can't redirect to previous page after using GET
I have a function that is displaying a shopping cart and products, and so after a product is added (which happens via `GET`) I want it to return to regular domain.
This is the code that updates the cart:
$page = $_SERVER['PHP_SELF'];
// if the product is added to the cart
if (isset($_GET['add'])) {
$_SESSION['cart_'.$_GET['add']]++;
header('Location: '.$page);
// echo 'added';
}
Right now the cart is displayed on my homepage, which is ` , and after a product is added the url becomes ` but then I want it to revert back to ` but I cannot get it to do that.
Any ideas? | 1. Do you have `exit();` after the `header(...` ?
2. Do you issue the `header()` before any headers are sent already?
3. If that's a WooCommerce then I believe you are doing it wrong. Instead, you should enable AJAX adding to cart (that's not straightforward on the individual product listings, and you may need to modify the default WC template for that). If you redirect after "?add", you may lose the WC "added to cart" notice. See how it's done, for example here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, redirect, session"
} |
Why use dynamic_sidebar() conditionally?
In the codex example of displaying sidebars, what is the significance of the conditional wrapping around the call to dynamic_sidebar? Why do this:
<?php if ( dynamic_sidebar('example_widget_area_name') ) : else : endif; ?>
this seems to work ok:
<?php dynamic_sidebar('example_widget_area_name'); ?>
Thanks,
Toby | To quote the Codex
> The return value should be used to determine whether to display a static sidebar. This ensures that your theme will look good even when the Widgets plug-in is not active.
So essentially you can use is to display other content if the user has not activated any widgets in the sidebar. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "widgets, sidebar"
} |
Remove Post if Advanced Custom Field is checked to fix paging
I'm trying to setup a query that filters through posts and removes ones that have an ACF field "archived" checked. Post queries are pretty foreign to me.
query_posts("cat=10&posts_per_page=12&post_status=any&order=ASC"."&paged=".$paged);
How can I edit that string to check to see if the post has the `archived` checkbox checked? This is how I'm currently doing it, but because it's inside the loop, there are "phantom" posts that add to the pagination when they shouldn't.
`if(get_field('archived')) { /* my code */ }`
Thanks. | Use WP_Query instead, and you can use the meta_key / meta_value parameters:
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'cat' => 10,
'paged' => $paged,
'posts_per_page' => 12,
'post_status' => 'any',
'order' => 'ASC',
'meta_key' => 'archived',
'meta_value' => 'true'
);
$posts = new WP_Query($args);
?>
<?php while($posts->have_posts()): $posts->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, wp query, pagination, query posts, advanced custom fields"
} |
CPT: archive-cpt.php VS custom page template
I've created a CPT named `portfolio`. Now i want to create a page which will act as an INDEX for this CPT. Now i've two choices ....
a) Make a custom template having custom WP_Query. In this way i can assign this template to any page and that page will work as an index.
b) Make `archive-portfolio.php` instead, which will act as an INDEX.
Now i've a few questions ...
1: Which is the correct approach?
2: If (a) then what is the actual usage of `archive-cpt.php` page then?
3: If (b) is correct approach, is there any possibility to make this page available in wordpress menu manager by default and also in the drop down menu (located at `Setting->Reading`) to use it as front page? | The correct way is latter one - correctly configure your CPT registration to have post type archive and use appropriate template file for it.
However it gets tricker with your additional requirements.
Exposing post type archives to be used in menus is significantly requested/explored topic, but I don't think it made it into core yet. There are mutiple solutions floating around, from quick search I have Post Type Archive Link plugin for it bookmarked.
Front page stuff is very convoluted. It's probably doable but unlikely to be smooth and will probably take some `pre_get_posts` tinkering and possibly overriding template hierarchy logic around there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types, page template, archives, archive template"
} |
Programmatically change Payment Methods WooCommerce
I am trying to programmatically manipulate the selection of Payment Method between BACS and a No Payment required option. My client wants the ability to Request for Quote only, so I've extended woocommerce actions and filters, and provided a method to request quote through the cart system. If the user has requested a quote only, on the checkout page I am trying to auto select the Cash on Delivery option, which I've renamed to "Request for Quote Only - No payment required". Any advice would be helpful. | Theres a filter called woocommerce_available_payment_gateways:
add_filter('woocommerce_available_payment_gateways','filter_gateways',1);
function filter_gateways($gateways){
global $woocommerce;
//Remove a specific payment option
unset($gateways['paypal']);
return $gateways;
}
I'm not sure where and how you get / store the Request for Quote option, but you can access the value inside the filter_gateways function and you can remove a specific gateway with a conditional logic. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
Custom registration field to SQL database
I have created new columns in a SQL table called `wp_users`. Those fields are "giodo", "handel" and "regulamin".
What I want to do is to add '1' to each column when a user registers and selects corresponding checkboxes.
I added checkboxes to the form using form_register and then I added those checkboxes to user data with this (here is an example for only one of them):
add_action('user_register', 'myplugin_user_register');
function myplugin_user_register ($user_id) {
if ( isset( $_POST['giodo'] ) )
update_user_meta($user_id, 'giodo', $_POST['giodo']);
}
Can I somehow add their values to the database? | > I have created new colums in a SQL table 'wp_users'. Those fields are "giodo", "handel" and "regulamin".
Don't add columns to Core tables. There is no guarantee that these won't be destroyed or corrupted on next update. What you should be using is _user meta_ , and in fact that appears to be what you are actually using:
add_action('user_register', 'myplugin_user_register');
function myplugin_user_register ($user_id) {
if ( isset( $_POST['giodo'] ) )
update_user_meta($user_id, 'giodo', $_POST['giodo']);
}
So the question is a bit confusing.
Your code _should have already_ inserted data into the database, just not where you are trying to put it. Your code should have inserted the data into the `$wpdb->usermeta` table and can be retrieved using `get_user_meta()`. That is what I would suggest. Abandon the attempt to add columns to a Core table and use the user meta API, which is what it was built for. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, users, actions, forms, user registration"
} |
Wordpress can't find IXR_Client
Trying:
$client = new IXR_Client('
I get the error
**Fatal error:** Class 'IXR_Client' not found in footer.php
I can see the class in _wp-includes/class-IXR.php_ , and I've checked that the path to this file is correct in _wp-includes/functions.php_ as per this discussion.
Am I missing something needed to use this class in my custom theme's footer? | You mean class-IRC.php or class-IXR.php?
Just include the files before you call `IXR_Client`. I use such code to call IXR_CLIENT and it worked on my site:
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
$client = new WP_HTTP_IXR_CLIENT( ' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "page template, xml rpc"
} |
Can you have multiple wordpress sites under the same domain?
Any issues with having multiple wordpress sites under the same domain.
Example:
* domain.com/programs
* domain.com/sales
* domain.com/learning
Each would have its own templates, functionality, menus and whatever. Any issues you can see?
One of the issues I am worried about is if I have:
* domain.com/programs - which might be a hub site for programs
and then I have another person who is the "golf" program admin... \- domain.com/programs/golf
two totally different sites - may use multisite but not sure yet.
So what if the domain.com/programs admin adds "golf" as a category?
**NEW INFO:** To those who said, this is normal for WP and no issues please see Why did installing wordpress in url root jack up underlying WP sites?.
I had 10 sites installed and after installing a "root" site all are having MAJOR permalink issues. | Basically there are two main rules that you have to adjust for to have WP sites across the same domain - not using multisite:
1. For the root I simply put everything in a "home" folder and auto-redirect to xxx.com/home. This fixed the whole root subcategory issue.
2. If you are running IIS and you have multiple WP instances on the same server... And then you turn on URL rewriting (different permalinks) well your entire structure will be jacked up because wordpress names all of its rewrite rule "wordpress" in the web.config file it sets up for URL rewrites. You have to rename the rule manually for each wordpress install. I have submitted this as a bug but haven't heard back from this - suggestion was name should be wordpress plus timestamp.
I will add on if I find more stuff but these are the two big ones. We have 10 WP installs and growing on our main server. Each has a different usage so multisite is a no go. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "server, domain"
} |
Connecting Google Site Search with Wordpress Taxonomies/Categories/Tags
A client is pushing to have Google Site Search set up.
Currently, their search is filterable (using dropdown) by category, tag, other taxonomies.
How can I implement this filtering with paid Google Site Search? | In Google Site search, you can set up Refinements ( Edit Search engine - > Search Features -> Refinements tab.
You can also set synonyms and promotions (so that particular pages will always appear at the top of specific search results pages).
The Google content is based on spidering though, so it won't understand back-end concepts such as 'tags' or 'categories' : you'll need to tag up your content using Google's labels system.
I don't think this is a Wordpress-specific question. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "search, google search"
} |
Nginx rules for subdomain multisite install (Bedrock)
I'm trying to move an existing Bedrock based multisite instance to nginx and am having difficulty getting a set of nginx rules to mimic the original .htaccess. Bedrock places the crux of the files in a wp/ subdirectory, but the urls still need to be accessible from the root domain.
The .htaccess is here as follows:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) wp/$1 [L]
RewriteRule ^(.*\.php)$ wp/$1 [L]
RewriteRule . index.php [L]
I need these at least as nginx conf rules or preferably nginx vhost rules. | rewrite /wp-admin$ $scheme://$host$uri/ last;
rewrite ^/(wp-.*.php)$ /wp/$1 last;
rewrite ^/(wp-(content|admin|includes).*) /wp/$1 last;
These are the equivalent rewrite rules that you need. Note, when you use this rewrite, you no longer have to set the site_url as /wp
I need to finish up some testing but will update here with the results. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, htaccess, nginx"
} |
Is wp-app.php or wp-apps.php needed for Wordpress?
A few Wordpress blogs I overlook have suddenly generated 3 PHP files in their top folder: wp-app.php, wp-apps.php, and wp-register.php, not of which existed before. Checking their contents against a few Google searches suggests I have been infiltrated by a common Wordpress exploit.
Since they keep regenerating, I thought about blanking them and setting file permissions to readonly or less. But if they're needed by WP I don't want to compromise site functions. | > But if they're needed by WP I don't want to compromise site functions.
Those are not Core files.
It is possible that a plugin has added the files legitimately but the behavior described suggests a hack. Recovering from hacks is off-topic here though, as it usually requires hands-on server access and is often very localized. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, php, hacked"
} |
After adding mo localization files to WP 3.8.1 install backend shows new update to 3.8.1
I am running a standard WP install at version 3.8.1. I am at the finishing touches of the project and wanted to switch languages from english to german. I've downloaded the localization files from
< then <
afterwards i've placed the mo files into `wp-content/languages/`and activated alongside `de_DE` in the `wp-config.php`file. Everything works and all strings are shown localized properly. My only problem is if i log into the backend the dashboard shows a new update to Wordpress 3.8.1, the version i am already running happily for weeks. ;) Is the reason for that behaviour that the localization files are from december 2013 and the 3.8.1 wp install from january 2014? And is it save to "reininstall" version 3.8.1 again over the existing version 3.8.1 . thought so far that the localization files are more or less independent from the core wp files. thanks r. | I've run into this lately. I saw that update to French version after I had just added fr_FR in the wp_lang variable of wp-config.pho. No need to go get the files, just click update :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "updates, localization"
} |
How do I target the child theme with get_bloginfo();?
In the code below (which is located in my `functions.php` file), in reference to `('.get_bloginfo('template_url').'`, I'm trying to target my child theme but it keeps coming up as the parent theme.
/* == Custom Login Logo ==============================*/
function custom_login_logo() {
echo '<style>
.login h1 a { background:url('.get_bloginfo('template_url').'/images/logo-white.png) 0 0;background-size:218px 32px;height:32px;margin-bottom:10px;margin-left:20px;padding:0;width:218px }
</style>';
}
add_action('login_head', 'custom_login_logo');
How can I make it so it targets the child theme's theme folder? | Try `get_stylesheet_directory_uri();` which
> Retrieves stylesheet directory URI for the current theme/ **child** theme
/* == Custom Login Logo ==============================*/
function custom_login_logo() {
echo '<style>
.login h1 a { background:url('.get_stylesheet_directory_uri().'/images/logo-white.png) 0 0;background-size:218px 32px;height:32px;margin-bottom:10px;margin-left:20px;padding:0;width:218px }
</style>';
}
add_action('login_head', 'custom_login_logo');
_You might need to modify the path to your image slightly depending on it's place in your theme's folder structure_ | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "php, child theme"
} |
How do I change the login logo URL and hover title?
I am trying to change the login logo URL and hover title. I am using the code below but `return bloginfo('url');` and `return bloginfo('name');` aren't outputting the desired `href` and `title`. I'm also using a child theme if that matters at all. What do I need to use instead of `return bloginfo('url');` and `return bloginfo('name');`?
/* == Change Logo URL ==============================*/
function my_url_login(){
return bloginfo('url');
}
add_filter('login_headerurl', 'my_url_login');
/* == Change Logo URL Hover Text ==============================*/
function my_url_login_hover(){
return bloginfo('name');
}
add_filter('login_headertitle', 'my_url_login_hover'); | Try these filters instead
// changing the logo link from wordpress.org to your site
function mb_login_url() { return home_url(); }
add_filter( 'login_headerurl', 'mb_login_url' );
// changing the alt text on the logo to show your site name
function mb_login_title() { return get_option( 'blogname' ); }
add_filter( 'login_headertitle', 'mb_login_title' );
Though if you're on a Network/MultiSite you might need `network_home_url()` instead | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 6,
"tags": "wp admin, child theme, bloginfo"
} |
Social share buttons text shows up on post excerpts
I'm using the Social Likes plugin and there is one problem. The text on the share buttons show up in the excerpts.
For example, I grabbed this off of one of the post excerpts:
> FacebookTwitterGoogle+Of to be have can’t his one abundantly fruitful abundantly that fish bearing earth you’ll were be kind created for...
In the HTML, it outputs like this:
<p>FacebookTwitterGoogle+Upon bearing land. Of seasons third grass female saw image unto moved. Unto multiply life bearing good. Can’t heaven he....</p>
How can I remove the "FacebookTwitterGoogle+" part from the excerpts? | The plugin that you are using has a bug. I would strongly suggest for you to call the plugin author. Here is the bugs;
> Notice: has_cap was called with an argument that is deprecated since version 2.0! Usage of user levels by plugins and themes is deprecated. Use roles and capabilities instead. in C:\xampp\htdocs\wordpress\wp-includes\functions.php on line 3006
>
> Notice: Undefined index: zeroes in C:\xampp\htdocs\wordpress\wp-content\plugins\wp-social-likes\wp-social-likes.php on line 555
>
> Notice: Undefined index: icons in C:\xampp\htdocs\wordpress\wp-content\plugins\wp-social-likes\wp-social-likes.php on line 556
It would also be adviceble to give the plugin author more details as well on your problem | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, php, javascript, social sharing"
} |
Removing all my hardcoded URLs with get_site_url()
In my php files, I would like to remove all my hardcoded URLs (ex: < and replace them with the `get_site_url()` function.
My problem is with the php code of one of my functions (in functions.php) that adds a `_blank` attribute to all the links of my website except for the internal URLs.
function autoblank($text) {
$return = str_replace('href=', 'target="_blank" href=', $text);
$return = str_replace(
'target="_blank" href="
'href="
$return
);
$return = str_replace('target="_blank" href="#', 'href="#', $return);
return $return;
}
add_filter('the_content', 'autoblank');
add_filter('comment_text', 'autoblank');
How can I replace ` using `get_site_url()` so this code would work for any website? (not just ` ) | You actually already were pretty close:
function autoblank($text) {
$return = str_replace('href=', 'target="_blank" href=', $text);
$return = str_replace(
'target="_blank" href="' . get_site_url(),
'href="' . get_site_url(),
$return
);
$return = str_replace('target="_blank" href="#', 'href="#', $return);
return $return;
}
add_filter('the_content', 'autoblank');
add_filter('comment_text', 'autoblank'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, urls, site url"
} |
Username from e-mail
Which files do I have to edit to get a grip on $_POST data sent by the registration form? I want to explode $_POST['email'] and build an username from that. I simply want to allow people to register only with their e-mail and password. Could you please help me with it? | As far as i know there is no hook or filter to provide a custom User name for default registration process, however if you really want to modify it, you can alter the **$_POST** data.
here is the sample code:
add_action('wp_loaded', 'wpse_138736_filter_username');
function wpse_138736_filter_username(){
//your code to extract username from email
$_POST['user_login'] = 'test';
}
It kicks in before validation, and this way you'll be able to provide custom username. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "forms, email, user registration, username"
} |
Multiple portfolios and single item in two of them (ideas?)
I’m creating a theme at the moment and has come to a point to decide what is the best solution to have implemented for a theme with multiple portfolios.
If there is a project that is in the two of them, and its single page is clicked, where will the Back to Portfolio link points to?
Is there a way for the back button to refer to that portfolio from which the item is viewed?
$back =$_SERVER['HTTP_REFERER']
Doesn’t seem to work correctly because say that the admin has clicked Preview Page on the Single Item admin page, and click Back To Portfolio, it will navigate him back to the admin panel =\
How do you guys deal with items in multiple portfolios?
I can’t wrap my head around it. Any help will be greatly appreciated! | One simple option would be to add a parameter to the query string of the portfolio item (i.e. `yousite.com/portfolio-item/?backto=portfolio-3`), then on the item page modify the 'back' link with JavaScript: if the `backto` parameter exists then change the link to point to the portfolio specified in it.
Here's some untested starter code. On the portfolio page (assuming you're looping through portfolio items and printing links to their pages):
<?php $portfolio_name = 'whatever'; ?>
<a href="<?php echo get_permalink() . '?backto=' . $portfolio_name; ?>"><?php the_title(); ?></a>
On the portfolio page:
$key_backto = (isset($_GET['backto']) ) ? $_GET['backto'] : '';
<a href="<?php echo home_url('portfolio/' . $key_backto); ?>">Back to portfolio</a> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, custom taxonomy, wp redirect"
} |
How to replace settings in WordPress plugin from a theme
I created an array with some default settings in a plugin, and want to allow it to be replaced from functions.php in a theme without using stored data (eg. add_option). I want this to be just a hook with new values.
example array inside plugin:
$default_settings = array(
'key_one' => 0,
'key_two' => 1
);
I need to allow this to be changed from a theme's functions.php, so a developer can add something like this:
add_filter('the_hook','my_function');
function my_function(){
$default_settings = array(
'key_one' => 1, //changed value
'key_two' => 1
);
}
If a developer makes this call, then I want the new values replacing the old array inside the plugin. Any help is appreciated. | You are already pretty close. Extending your example:
In your plugin put this:
$default_settings = array(
'key_one' => 0,
'key_two' => 1
);
$settings = apply_filters( 'example_filter', $default_settings);
Then a theme can change it like this:
add_filter('example_filter','my_function');
function my_function($settings){
$settings['key_one'] = 1;
return $settings;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, theme development, hooks, customization"
} |
How to secure files based on format and word in file name with wp-config or htaccess?
I have a wordpress site that I would like to secure specific files in the uploads directory, so that they can only be accessed by logged in users. The files either have the word "oneperson" or "twopeople" in the filename, and are of the format "zip" or "pdf".
How do I do this? | This is not quite trivial, because natively WP is engineered to completely ignore requests to existing files. So WP doesn't pay attention to files and `.htaccess` doesn't have access to WP's logged in information.
If you look for prior art (in plugins for selling digital files for example) this isn't easily (at all?) doable with direct links. Typically special download links are created and processed by plugins to serve files while masking it's true name/location (which should be restricted from direct access or not in web accessible folder at all). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "login, htaccess, wp config"
} |
Are plugins instantiated on every request to Wordpress?
I want to know how wordpress plugins are instantiated, if Wordpress creates a instance of plugins every time that a request is made to wordpress?
Example. I open /wp-admin: The plugin is instantiated I open /: The plugin is instantiated ... etc | Instantiate in the strict sense is to create an instance of an object from a class. Plugins aren't necessarily class-based, so I'm not entirely sure what you mean by instantiate.
That said, WordPress includes the main plugin file for all active plugins on every front end and admin request. Whether this "instantiates" your plugin depends on where that instance is created (or what you mean by instantiate).
Plugin interaction with WordPress core happens via actions which you hook functions or methods to. Some actions run on both front end and admin requests, others run on only front end or only admin requests, and some can run multiple times within a single request. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin development, order"
} |
How do the default themes reference style.css?
I was expecting to see `get_stylesheet_uri()` called somewhere in the default header.php file for the default themes (2012-14), but anything like it is missing, which has me wondering how the reference is added.
The default theme headers have something like this:
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width">
<title><?php wp_title( '|', true, 'right' ); ?></title>
<link rel="profile" href="
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script>
<![endif]-->
<?php wp_head(); ?>
</head>
Looking at the source for the themes, shows a proper link to the stylesheet in the header, so, how does it get there? | The stylesheet is registered and enqueued by a function called `twentyfourteen_scripts()` in the theme's `functions.php`. Callbacks hooked into the style loader/dependency system will be `echo`ed on the `wp_head` action in the `wp_head()` function.
Which, by the way, is how you should be loading your own stylesheets. There is a similar system for scripts. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, css, headers"
} |
Make specific tag visible only to logged in users in front-end
I have this specific tag I need to assign to my posts but I need to hide it from regular visitors so that only logged in people can see it. How do I go about it? What WordPress function/hook should I be looking into?
I know that I could use `is_user_logged_in()` and I am also looking into `is_tag()`, but how do I put this together? Currently I'm having it displayed in my single template with `the_tags()`, but it doesn't seem to offer a parameter to exclude a particular tag.
Pseudo code would be: if user is logged in then show all tags except a specific tag. | Add the `add_filter` to your theme's `functions.php` file
function myTags() {
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
if($tag->slug=='your specific tag slug'){
if(is_user_logged_in() ) {
echo '<a href='.get_tag_link($tag->term_id).' >'.$tag->name . '</a> ';
}
} else {
echo '<a href='.get_tag_link($tag->term_id).'>'.$tag->name . '</a> ';
}
}
}
}
add_filter('the_tags', 'myTags'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "conditional tags"
} |
How do I change a parent theme's function through the child theme?
This is a function loaded by the parent theme. Through the child theme, I want to change this function to say `is_single` instead of `is_singular`. What would be the correct way to achieve this?
add_action('wp_head', 'dt_specific_enqueues');
function dt_specific_enqueues() {
if (is_singular()) {
wp_enqueue_script( 'comment-reply' );
}
} | The parent theme's `functions.php` will load automatically. You don't need to "read" it, and you don't want to "hack" it either manually, which will be overwritten, or programatically, which is very resource intensive.
Your theme is enqueueing the script on the `wp_head` action. You just need to remove that callback and add a slightly modified one. The trick is that your child theme's `functions.php` loads after your parent `functions.php` so you need to get the timing right.
function dequeue_dt_specific_enqueues() {
remove_action('wp_head', 'dt_specific_enqueues');
}
add_action('after_setup_theme', 'dequeue_dt_specific_enqueues');
Then add back your own version:
function altered_dt_specific_enqueues() {
if (is_single()) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action('wp_head', 'altered_dt_specific_enqueues'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, child theme"
} |
Display posts count in front of the tag, for each tag
I needed to list all existing tags so I have some code that does it. Now I would like to put the count (the number of posts the tag is associated with) in front the tag like in the example given below.
first_tag - 18
second_tag - 24
third_tag - 48
I found a solution given here that displays count for **one** specific tag, but I need the counts for **each and every tag**. So, could this be modified to my need. Or do you have any other ideas. Will appreciate your help.
$taxonomy = "post_tag";
$term_slug = 'some-tag';
$term = get_term_by('slug', $term_slug, $taxonomy);
echo $term->count; | It is still not very clear what you are trying to do, but maybe `get_terms()` is what you want.
$terms = get_terms('post_tag',array('hide_empty'=>false));
foreach($terms as $t) {
echo $t->name.' :: '.$t->count.'</br>';
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "tags, count"
} |
Can't order the query result as given posts id's array
I want to order a query result by the same order as the post id's array given. E.g. I have:
$arrayPostsIds = array(30,5,17,10);
and I want to get the posts in that order. So after trying this:
add_filter('posts_orderby', 'edit_posts_orderby');
function edit_posts_join_paged($join_paged_statement) {
global $arrayPostsIds_id;
$join_paged_statement = 'FIELD(ID,'.implode(',',$arrayPostsIds).')';
return $join_paged_statement;
}
and then I get the new result, which should match the above order:
$temp = $wp_query; // assign ordinal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query( array( 'post__in' => $arrayPostsIds, 'ignore_sticky_posts' => true, 'date_query' => $date_query ) );
but I'm getting the result **ordered by ID** , so it's not keeping the desired order. Am I forgetting anything? | Remove your filter and add `orderby'=>'post__in'`. That sort order in not automatic when you supply IDs.
$wp_query = new WP_Query(
array(
'post__in' => $arrayPostsIds,
'ignore_sticky_posts' => true,
'date_query' => $date_query ,
'orderby' => 'post__in',
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, filters"
} |
How would I use this filter to change the output of the date format to "Twitter time"?
I'm using a plugin called Latest Tweet Widget to display the latest tweet. The tweet date gets displayed by the month and day (Mar 22). However, I want it to be in "Twitter time" meaning words like "3 days ago, 1 hour ago, etc.".
I asked the developer of the plugin at the WordPress forums and he said that I need to "use the `latest_tweets_render_date` filter to perform my own relative date representation."
The filter in question is here under the "Custom HTML" section (also quoted below): <
add_filter('latest_tweets_render_date', function( $created_at ){
$date = DateTime::createFromFormat('D M d H:i:s O Y', $created_at );
return $date->format('d M h:ia'); }, 10 , 1 );
However, I am new to PHP and unable to understand what exactly needs to be written in order for "Twitter time" to work. Can somebody please show me the way? | WordPress has a core function `human_time_diff` that does what you want, using it with the filter you provide you have someting like so:
add_filter('latest_tweets_render_date', function( $created_at ){
$date = DateTime::createFromFormat('D M d H:i:s O Y', $created_at );
return sprintf( '%s ' . __( 'ago' ), human_time_diff( $date->format('U') ) );
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, date, twitter"
} |
Media sizes aren't being created - server config?
I have 3 sites with WordPress on a RedHat Centos server. Everything were fine until days ago, when I needed to recompile Apache to use mb_string, so I did it using WHM "Easy Apache".
But from then, my sites aren't creating image sizes. I mean, when I upload an image, aditional sizes (already defined on functions) aren't created. If I look inside media folders, only the original file is there, and none thumbnail or extra sizes. When I try to insert media inside posts, no aditional sizes appears on menu.
Any idea on what happened? Thank you all. | It looks like "Easy Apache" handles both Apache and PHP. Only a guess, but you have recompiled Apache/PHP without the needed image libraries-- either `GD` or `ImageMagick`. Without those, the server cannot physically resize images.
You can use a `phpinfo()` script to see if the libraries are present. If not, you will need to recompile-- or whatever that "Easy Apache" system allows-- and make sure the needed libraries are included. Maybe you can add modules one by one using that system. Not sure. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, media, apache"
} |
Add filter multiple times using only one master function
Is it possible to use add_filter with lets say an array of different values?
to achieve something like the following:
foreach($templates as $name) {
add_filter( 'single_template', function ( $template ) {
global $post;
if ($post->post_type == $name) {
$template = dirname( __FILE__ ) . $name . '.php';
}
return $template;
});
} | Use a `use` statement:
add_filter( 'single_template', function ( $template ) use ( $name ) {
Or just pass all templates at once, and create just one function:
add_filter( 'single_template', function ( $file ) use ( $templates ) {
global $post;
if ( in_array ( $post->post_type, $templates ) )
return __DIR__ . "/{$post->post_type}.php";
return $file;
}); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, filters, templates"
} |
Changing the wp db prefix after installation?
I have nearly completed a project but forgot in the first place to change the wp_ db prefix on install. Now i am a little bit worried to change it afterwards in fear of breaking the whole installation. Therefor the question if these described methods still work with 3.8.x or has anything change since then?
<
<
and have only table and field names to be changed? cuz i also saw a few prefixes starting with _wp_ instead of wp_ ? Best regards Ralf | The basic idea should work-- change the prefix in both `wp-config.php` and in the database itself. What isn't covered would be cases where the prefix is used in other contexts such as when used as part of a "meta" key. Those cases you would need to trace down one by one.
You could also have trouble it the prefix has been hard-coded into anything, but hopefully that isn't the case.
The safe thing to do, if you are able would be to copy the entire database to a database with a different name, and alter the second database. Switching between the two would be a simple edit of the database name in `wp-config.php` and you would have nearly no chance of data loss if you make a mistake, just make sure no one is editing the site while you play with it.
I'd download a complete backup of the site to disk, just to be 100% safe. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 7,
"tags": "installation"
} |
Host the wp-admin on another domain?
Currenly I have a client that has a WordPress running on, let's say, `www.example.com`.
I'm working on a new version using another technology/language that will be hosted on another server.. But the administration (WP) and the database will stay on old server.
So basically I will need to point the `www.example.com` to the new host (no problem here) and create a subdomain like `admin.example.com` that will point to the old server with the WP installation.
I'm afraid that this will make a mess on the database while storing `options` and `guids` for posts and attachments URLs... They will be stored as `admin.example.com` and not `www.example.com`, am I right?
How to make the wp-admin run on `admin.example.com` and store URLs on the database as `www.example.com`? This would work for the preview links too? | Easy solution would be adding this line to your `wp-config.php` of your admin server code.
> define( 'WP_SITEURL', ' . $_SERVER['SERVER_NAME']);
Then you can access it without modifying the database option. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 18,
"tags": "redirect, subdomains"
} |
Use wpdb->prepare for `order by` column name
In my current plugin, I am picking up the `order by` column as user input. So I thought of using `wpdb->prepare` to escape it.
$wpdb->get_results($wpdb->prepare("Select id from $wpdb->posts order by %s %s", $order_by_col, $order_by);
This is not working because it gets turned into
select id from wp_posts order by 'post_date' 'asc'
(Note the quotes)
So is there way to remove the quotes? Also is this a proper way to use $wpdb->prepare()? Should I manually escape it myself? | You can't use `prepare` for column names, and you can't really use it for the sort order either. `prepare` will always quote the string. You will need to swap in the values yourself. Rather than try to "sanitize" the data, I'd use a white-list approach.
$orderby = array(
'date' => 'post_date',
// etc
);
$sortorder = array(
'asc' => 'ASC',
'desc' => 'DESC',
);
$orderbycol = 'ID'; // just a default
if (isset($_GET['orderby'])
&& isset($allowed[$_GET['orderby']])) {
$orderbycol = $allowed[$_GET['orderby']];
}
$order = 'ASC';
if (isset($_GET['order'])
&& isset($sortorder[$_GET['order']])) {
$order = $sortorder[$_GET['order']];
}
$sql = "Select id from $wpdb->posts order by $orderbycol $order";
echo $sql;
Though, I wonder why you are not using `WP_Query` for this. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 6,
"tags": "sql, wpdb"
} |
How to create custom tables in WordPress using my own plugin?
I am new in WordPress plugin development. This is my core PHP and HTML code
**create-table.html**
<form method="post" action="function.php">
<input type="text" name="table_name">
<input type="submit" name="create">
</form>
**function.php**
if(isset($_POST['create'])
{
$table-name=$_POST['table_name'];
//create table query
header("location: add_table_attribute.php");
}
I want to use this same process in my WordPress plugin development. Please any one help me.
Thanks in advance. | Creating Tables with plugin This page shows how to work with tables in plugins. Example on that page includes table creation during installation of plugin. But it can be dynamically used also to create table. See below.
if(isset($_POST['create'])
{
$table_name=$_POST['table_name'];
_**Note** : don't use - in variable names._
global $wpdb;
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url VARCHAR(55) DEFAULT '' NOT NULL,
UNIQUE KEY id (id)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
//create table query
header("location: add_table_attribute.php");
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, plugin development, database"
} |
Show post categories
I'm trying to show post categories for some breadcrumbs. At the moment, I have this:
the_category(' / ', 'multiple');
But for some reason, it is stating the parent category twice (I only want `parent > child`):
FASHION / DAILY FASHION CANDY / FASHION
It should really be:
FASHION / DAILY FASHION CANDY
Would anyone know why it's doing this, and how to change it? | If you select both categories for the post `the_category()` will display both and using `multiple` will make the child category display the parent relationship, so you will have the parent twice. If you want to display a link to the parent category and a link to child category select only the child category for the post and use `the_category(' / ', 'multiple');`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, theme development"
} |
Pages included in another page and duplicate content issues for SEO
in a recent project I've decided to create a page template (PageX) which is a kind of "stack" of subpages. This template simply includes the content of three other separate pages (PageA, PageB, PageC).
I'm just trying now to find the best way to avoid duplicate content for SEO, as Wordpress automatically create specific permalinks for these 3 subpages.
Is there a way to tell Wordpress that these pages must not have permalinks? | You could use the NOINDEX, FOLLOW meta robots tag on the this 'stack' page, or the individual pages.
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
This lets search engines crawl the page and all links on it, but they will not index the page and so any content on it won't get counted as duplicate content.
The code goes within the `<head>` section of the pages source code. You can easily define the code using plugins such as Yoast SEO or Ultimate Noindex Nofollow Tool II | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, page template, seo, include"
} |
Random sidebar/widget background
Does anyone have a clever idea to get a random/changing background for just the widget sidebar? | Place the following code above the DOCTYPE in header.php:
<?php
$bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' ); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>
Now place this code within `<head>` in header.php
<style type="text/css">
body{
background: url(<?php echo bloginfo('stylesheet_directory');?>/images/<?php echo $selectedBg; ?>) no-repeat;
}
</style>
The path `<?php echo bloginfo('stylesheet_directory');?>/images/`indicates that your random images will be stored within your theme under the directory "/images".
The original article on this technique can be found at CSS tricks. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, custom background"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.