INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Custom loop by url
So currently I have this working for 'search' ie: if I do www.domain.com/search/query, it returns everything it finds on the word 'query'. I would like to utilize that loop/template I created within that search.php but change it to posts. Then query a specific post category if possible ie: www.domain.com/posts/category1
I'm think it all stems off changing
<?php get_template_part('loop', 'search'); ?>
Fairly new to wordpress so any help or suggestions is greatly appreciated! | You can customise the loop query to get results based on a search term - with $s being the search term;
<?php // Post Query
$args=array(
's' => $s,
);
?>
<?php query_posts($args); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, loop"
} |
Adding Pinterest Script Before Closing Body Tag
According to the Pinterest website in order to add the Pinterest button to any page I have to add the following just below the closing body tag:
<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>
What's the best way to do this?
Should I follow the link, grab the script and use wp_enqueue_script? Or can I somehow include the script element another way?
Thanks. | Yes, you have to use wp_enqueue_script function. Pass `$in_footer` argument as `true` and your script will be added before closing body:
function my_scripts_method() {
wp_enqueue_script( 'pinterest', '//assets.pinterest.com/js/pinit.js', array(), false, true);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp enqueue script"
} |
What is the advantage of separating wp_users and wp_usermeta table?
I want to know why Wordpress designed their database with two tables separating users and meta from each other. Wouldn't it be better if first_name, last_name, nickname, description, and capabilities are in the wp_users table?
SO what's the advantage for doing this separation? | The meta table is build to allow custom user meta. If anything would be in just one table a plugin developer had to add a new column to the table for each meta data or the data had to be stored as serialized arrays/objects which would made them unsearchable.
Short: Performance and flexibility. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "database"
} |
Functions.php code that only runs on localhost?
I would like to run an add_action in functions.php only if the theme is being loaded from my localhost development site. How would I get this to run only on localhost?
function livereload(){
?>
// mycode
<?php
}
add_action('headway_body_close', 'livereload'); | This is the corect answer
if ( $_SERVER["SERVER_ADDR"] == '127.0.0.1' ) {
function livereload(){
?>
// mycode
<?php
}
add_action('headway_body_close', 'livereload');
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "functions, localhost"
} |
styles/default.css in markup, where does it come from?
I have the following line under the `head` tag but I don't have the file `styles/default.css` in my theme and consequently get a loading error in browsers. I'd like to eliminate this line but I don't know where it comes from. I tried to disable all plugins but it still appears. Is this a standard inclusion in WP?
`<link type="text/css" rel="stylesheet" href=" | Found it with `ack default.css`. In someone else's file that I had added to the theme. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "errors, 404 error, css, customization"
} |
How to Custom Edit Post Title & Permalink Slug?
I'm trying to build some functionality where if you're logged into an admin account you'll see a small 'edit' link next to each post title. clicking will use jquery to create 2 form inputs - 1 with the current post title and the other containing the current slug.
I'd ideally like to then allow admins to edit any post/slug from the post page itself using Ajax. To accomplish this I need to find how to update MySQL when the user hits "save". What would be the best way to go about doing this?
I think I'll need to create a new .php file which is called by JavaScript, passing in the title/slug vars. But I'm not sure which Wordpress core files have the SQL code for updating a post title.
Any help would be greatly appreciated! | Have a look at wp_ajax action hook for invoking your action. Then use update_post to update the title and slug. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, wp admin, ajax, slug, title"
} |
What is theme-compat?
I have noticed that `wp-includes/theme-compat` directory.
So, what is it?
Is it a theme? | The `theme-compat` directory is comprised of a set of **deprecated** (since WordPress 3.0) files that WordPress _used_ to use as fallback template-part files, in case the active Theme failed to include them.
In other words, if a Theme used the `get_header()` template tag, but failed to include a `header.php` template-part file, WordPress would fall back to `/wp-includes/theme-compat/header.php`.
The template-part files in `theme_compat` are **deprecated** , unmaintained, incredibly old (by core/current-Theme standards), and should not be relied upon by any current Theme. | stackexchange-wordpress | {
"answer_score": 20,
"question_score": 15,
"tags": "themes"
} |
Not One 'Contact Form Plugin' will send email // Work
I've tried over a dozen 'Contact Form' Wordpress Plugins. None of which will function and send the form contents to any email. I'm working on top of the 'PremiumPress DirectoryPress Theme' I'm thinking that the issue might be, that this theme came with a Contact Form Template (Very Terrible One), which I've removed in the code awhile ago. So, any new plugins are conflicting with the old default ? | Disable all other plugins. Use the default theme. Try again. If it doesn't send, try sending to a different (eg gmail) address. If that still doesn't work, verify that sendmail is installed. If it is, check and see if a basic sendmail php script will work. If that still doesn't work or sendmail isn't installed, you may need to contact your host regarding the issue.
If you find it will send to a gmail account, but not to your own @yorudomain account, chances are there's a DNS or potentially an anti-spam issue that's blocking the emails. You may also want to see if there's an outgoing box for sendmail, or error log which shows you what the issue might be. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, contact"
} |
What is the action hook for save media-form on gallery tab?
I want to save a meta data to post parent when the media-form on gallery tab is saved( The submission button is "Save All Changes"). Which action hook can I use? | For updates it is `'edit_attachment'` and for new attachments `'add_attachment'`.
There is no action dedicated to images coming from the gallery tab, but you could check the global array `$_FILES`. If there is a `$_FILES['async-upload']` it is _probably_ a request from the media popup. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "hooks, gallery, media library"
} |
Running hundreds of WP in multisite
We are starting to rack up the number of WP websites and we're looking to have a bit more control over all of them, would multi site be the correct way to go?
All the sites are running on different domains, different versions of WP and different plugins (with different versions of those). I don't want to blanket update all of the versions because I don't want to risk things breaking.
So with that in mind would the only benefit be that I would have a super admin access and be able to switch between the sites quickly? | yeah, if you cant upgrade to 3.0=> then you could use something like < that adds the functions to control multiply sites from "one dashboard".
Im running a big multisite for all my min-clients with separate domains etc. And its really nice to have that control of all the sites. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite"
} |
Filter query_posts by tag slug on "Tag Archive" page (when tag is 2 or more words)
I'm using the following to bring up a tag archive page:
<?php query_posts( "tag=". '' . single_tag_title( '', false ) . '' ); ?>
This works perfectly for all tags of one word only, but any tags of more than one word (eg: "tag one", slug: "tag-one") do not display.
Is it possible to query_posts by tag slug, rather than single_tag_title?
Thanks! | The `single_tag_title()` function returns the tag title while you need the tag slug or ID for use in `query_posts()`. This should get you started:
if ( is_tag() ) {
$tag = get_queried_object();
$tag_title = $tag->name; // Same as single_tag_title()
$tag_slug = $tag->slug;
$tag_id = $tag->term_id;
}
< | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "query posts, tags, archives, slug"
} |
wp_link_pages appearing after post content and not at bottom of page
This code worked perfectly! But my issues is that it removes text on pages. I just need the page numbering to appear immediately after the post and not at the bottom of the page. Any suggestions?
add_filter ('the_content', 'pagination_after_post',1);
function pagination_after_post($content) {
if(is_single()) {
$content.= '<div class="pagination">' . wp_link_pages('before=&after=&next_or_number=next&nextpagelink=Next&previouspagelink=Previous') . '</div>';
}
return $content;
} | Your call of `wp_link_pages` displays navigation immediately because `echo` argument is set to `1` by default, and it means to echo result. So try to add `&echo=0` at the ennd of `wp_link_pages` call:
add_filter ('the_content', 'pagination_after_post',1);
function pagination_after_post($content) {
if(is_single()) {
$content.= '<div class="pagination">' . wp_link_pages('before=&after=&next_or_number=next&nextpagelink=Next&previouspagelink=Previous&echo=0') . '</div>';
}
return $content;
}
Read more about `wp_link_pages` parameters in codex. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp link pages"
} |
Sticky posts don't show up first in custom loop
I'm using the following query in my frontpage template:
<?php $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args=array(
'paged' => $paged,
'category_name' =>'home,tumblr'
);
query_posts($args);
But for some reason, posts that are made sticky in either of these categories do not show up as the first posts in the output of the loop. It seems option is ignored somehow? How can I make sticky posts show up first? | **DO NOT USE`query_posts()` FOR CUSTOM LOOPS!**
Use `WP_Query()` instead.
<?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$custom_cat_query_args = array(
'paged' => $paged,
'category_name' =>'home,tumblr'
);
$custom_cat_query = new WP_Query( $custom_cat_query_args );
By default, `ignore_sticky_posts` is set to `0`, or _do not ignore_. So, the custom loop should handle sticky posts as per normal. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query posts, sticky post"
} |
Looking for a hook for post.php
First time posting here...
I am trying to figure out if there is a hook or action that I can use when a user goes to wp-admin/post.php... Basically when the user goes to post.php I want to check if there is a &from=1 variable and add that to post_meta
Thanks!
$from = $_GET['from'];
$post_id = $_GET['post'];
if($from == 1){
add_post_meta($post_id, 'EDITED', 'true');
} | You can add your code to the `init` action hook and check global `$pagenow` variable:
add_action( 'init', 'wpse8170_check_from_var' );
function wpse8170_check_from_var() {
global $pagenow;
if ( 'post.php' != $pagenow || ! isset( $_GET['post'] ) || ! isset( $_GET['from'] ) || 1 != (int) $_GET['from'] ) {
return;
}
update_post_meta( (int) $_GET['post'], 'EDITED', 'true' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "hooks, actions"
} |
Fire a hook programmatically
Is it possible to fire a wordpress hook programmatically? Specifically I'd like to have control of wp-insert-post. | To fire a hook you can use following functions:
1. `do_action` \- executes a hook created by add_action.
2. `do_action_ref_array` \- execute functions hooked on a specific action hook, specifying arguments in an array. This function is identical to `do_action`, but the arguments passed to the functions hooked to $tag are supplied using an array.
If you want to apply filters, you can do it by calling `apply_filters` function. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "hooks, wp insert post"
} |
Add extra fields to Add New Category page
I need to add an extra field to the Add New Category page. Currently it only has fields for Name, Slug, and Description. Essentially, I need to have a second description text box.
I use the current Description field at the bottom of each category page, but now I need to have additional information specific to the category (and different from the bottom) displayed at the top.
How can I add this additional field?
Below is what I am trying to achieve:
! | Ended up solving this with bainternet's plugin at < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "categories, custom field"
} |
Posts limit on homepage (genesis framework)
in home.php
// NOT working
query_posts('show_posts=3');
// NOT working
add_action( 'pre_get_posts', 'set_posts_per_page' );
function set_posts_per_page( $query ) {
$query->set( 'posts_per_page', 3 );
return $query;
}
genesis();
I searched a lot, almost always they say the 2nd solution. But i does not work for me, maybe because its genesis. Or is this outdated?
I don't want to use the custom grid stuff i just want to limit the posts on one page (the homepage in this example)
solution thx to @Milo:
its just working in functions.php and there i need a additional if is_home
/** reduce number of posts on homepage **/
add_action( 'pre_get_posts', 'set_posts_per_page' );
function set_posts_per_page( $query ) {
if ( is_home() )
$query->set( 'posts_per_page', 3 );
return $query;
} | 1) use `posts_per_page` to set number of posts 2) your `add_action` and its associated function needs to be in your theme's `functions.php` file, not the template.
the `pre_get_posts` action is the preferred method between the two, use that one. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, query posts, homepage, genesis theme framework"
} |
How to make WP_Query not to show irrelevant posts?
I'm using the following `WP_Query` arguments array:
$args = array( 'post_type' => POST_TYPE,
'tax_query' => array(
'taxonomy' => TAX,
'field' => 'slug',
'terms' => TERM
),
'posts_per_page' => 2
);
The problem is this query displays all the posts from `POST_TYPE` which have a `TAX` (any `TAX`) assigned to them but it's not limiting it to the `TERM` (particularly one term) taxonomy!
I just want the posts from the specific `TERM` taxonomy and nothing more! | You're one array short. The tax_query is an array of arrays.
$args = array( 'post_type' => POST_TYPE,
'tax_query' => array(
array (
'taxonomy' => TAX,
'field' => 'slug',
'terms' => TERM
),
),
'posts_per_page' => 2
);
See < for more. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom post types, custom taxonomy, wp query, query posts"
} |
Customize WordPress>Error Page
Is there a way to customize the WordPress>error page template so that the user isn't shown just a blank screen with text?
I'm not talking about 404, but when WordPress displays an error.
I'd like to style this page to match my theme. | You're probably talking about theming `wp_die()`, which is the function that produces those grey error pages with a white box of text in them.
**For a plugin solution** , you could try this plugin, which says it does what you want. Not sure about version support though--it says it only works up to 3.1.4.
**For a programatic solution** , you'll want to hook into the filter "wp_die_handler". So you can do:
add_filter('wp_die_handler', 'my_die_handler');
As far as code for the `my_die_handler` function, you could start by looking at the default die handler -- the function is called `_default_wp_die_handler`, and it starts on line 2796 of the core file `/wp-includes/functions.php`. You can copy the whole function to your plugin file (or your theme's functions file), rename it `my_die_handler`, and customize it from there. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 7,
"tags": "theme development, errors"
} |
Get list of WP Updates Across Sites
Is there a way to query a WP site to see the number of updates currently available? I'm not really looking for a list of the actual updates, just the number. This would be the total number of Plugin/Theme/Core updates, like it is listed in the WP admin menu.
I manage multiple WP sites across multiple servers and would like an easier way of knowing when updates are available, rather than checking them individually. | Old question but, I wanted to post this here for reference, since I never accepted an answer.
This functionality is now easily achieved using the Jetpack centralized dashboard. You can administer updates to all your connected WP sites.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "php, wp query, updates"
} |
Content generator for development site
Does anybody knows good plugin which can generate dummy posts/tags/categories/users and write dummy comments? I want to generate some content on my development (localhost) site. | I always use the Theme Unit Test that Theme Reviewers use to evaluate themes for the Repo. It's got pretty much everything you need to style/worry about.
And if I need to create batch content in a different way, then I use WP Dummy Content | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "plugins, plugin recommendation, content"
} |
Determine Registered Admin Menus
Is it possible to obtain a list of which Top Level Admin Menus have been registered via some plugin?
I'm talking about menus registered with: `add_menu_page();` | You can use the global variable `$menu` to see which top level menus are registered.
function determine_menus() {
global $menu;
//echo '<pre>'; print_r($menu); exit; // uncomment to see the array of menus in back-end
}
add_action('admin_init', 'determine_menus'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, plugin development, dashboard, add menu page"
} |
Can i have a single wordpress site to have two themes ( one for pc other for mobiles)
I have a wordpress site say at www.demo.com, now I have two themes one which I want to use this user is acessing the site from "PC" (computer) and a another theme, which is a full fledged mobile theme to be used only when the user is accessing from a mobile device ( such as an android phone, iphone, ipad or tablet).
I did some googling and found that one of the solution is to have two websites like www.demo.com : this will have a theme for users accessing from computers www.m.demo.com : this will have a theme for mobile users
But firstly is it possible to do what I am thinking that have a single site and the theme should change automatically after detecting the user's device.
Please help me out on this, any help/ideas/suggestion/criticism/ any thing will be appreciated.
Thanks | If you don't mind getting your hands dirty with code you could combine both themes into the same folder. IE: wp-content/themes/yourtheme/secondtheme
Then add the code in the header.php for your primary theme to check if its a mobile site and send the user to wp-content/themes/yourtheme/secondtheme/index.php
Probably a pretty big nightmare.
The proper way of doing this is to code the mobile theme into your theme. These type of themes are called "responsive" meaning they conform to what ever device is viewing them. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "themes, theme recommendation"
} |
Show Excerpts In Twenty Eleven Theme
I just need to create a blog I have done everything i guess, its showing posts but they are supposed to be kind of summary first and after click the whole post.
I already selected the "For each article in a feed, show summary" from reading option from dashboard
I already activated the hidden option of enabling excerpt, and typed some words to check but no luck..
I have replaced the `<?php the_content();?>` to `<?php the_excerpt();?>`
Might be i am missing something, it was simple every site I followed for the solution they told me so but i am not getting output
theme i am using is Twentyeleven and I dont want to use any plugin coz they(You and all word-press masters)say its simple. | To show excerpts on home page and all archive pages, open `content.php` and modify the following line:
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?>
with this:
<?php the_excerpt(); ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "excerpt, theme twenty eleven"
} |
Creating a Search Array From Multiple Tables
I'm working with a client's WordPress site that has user submissions (via TDO Mini Forms) from multiple countries, and they would like to be able to search for posts by region – Europe, Africa, Central America, etc.
There is a custom field already in place for the user's country of origin. I also have a separate table that maps countries to regions. What I want to do is make it so that the user can select Europe, for example, from a map, and have WP return any posts from countries that are mapped as EU.
What's the best way to accomplish this? Not only do I not want to reinvent the wheel, but WP can be very fussy about it search functions.
My first thought was to perform a search of the Regions table, return all of the countries as an array, and then use that array to perform a WP search, but I'm not finding how to do that without creating an AND search, which returns nothing.
Thanks for any help.
ty | You've got the right idea. If you get an array of country IDs within a region, you can pass that array to a meta query IN comparison:
$country_ids = array(1,2,3); // this would be the result from fetching countries associated with a region.
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'country',
'value' => $country_ids,
'compare' => 'IN'
)
)
);
$query = new WP_Query( $args );
EDIT- this is assuming the ID is stored, if you're storing the country names as the value, you should query with an array of the names. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "search, wp parse args"
} |
Apply a Meta tag to one page only
I'm working on a IP Locator Service, and I want to display a Customized Google Map which shows the visitor's location. It works fine here, but I don't know how to incorporate it into my Blog.
I've got the "html/javascript in Wordpress" Plugin, but I also need to apply a few Meta tags to the page. Is there any plugin/tweak that allows to add a meta tag _only_ to one page?
Please Help!!
**Edit: I also need to include javascript ( < script>< /script>). How can I do that?** | You have two options. Both involve using a conditional tag. I don't know which conditional you'll need to test for, hence the "{something}" placeholder. (If I had to guess, you may use the `is_page( $ID )` tag.)
## Edit your theme header file.
It's usually called `header.php`:
if( is_{something}() ) {
echo '<meta ......... />';
}
## Use the `wp_head` hook in your `functions.php` file
function wpse_54694() {
if( is_{something}() ) {
echo '<meta ......... />';
}
}
add_action( 'wp_head', 'wpse_54694' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, html"
} |
Gravatar alternative for Wordpress
I don't know whether it's something I'm doing wrong or an issue with the Gravatar website in general, but it doesn't seem to let me create an account (no error is given, the account just doesn't get created). There's no contact information that I could find for them to contact them.
Regardless, is there something that will provide the avatar functionality in a similar way that I can use (that works)? | How to contact Gravatar support
There are also several options( 1 , 2 ; just examples) for handling the avatars locally instead. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
pictures does not apeare in posts
I installed last version of wordpress by activating network. I can upload images or any media and insert into posts, But when I publish that, medias including images or any other media. My htaccess file includes:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
How can I see my pictures in my blog? Please help. | The correct `.htaccess` for a multi-site setup looks like this:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# uploaded files
RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule . index.php [L]
Note the rule for `files`: That’s how WordPress locates your images. You need also a `blogs.dir` directory in your `wp-content` directory. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "links, htaccess"
} |
How to do I get a list of active plugins on my wordpress blog programmatically?
I have 2 blogs, one which is multisite and one which isn't. I want to get a list of plugins active on both the blogs so I can compare them. On the multisite blog, I want to list the plugins which are enabled network-wide as well as site wide. | The activated plugins are stored in the options table of a WordPress Blog under the key `active_plugins`
so you can use `get_option('active_plugins');` of each blog and compare the arrays. | stackexchange-wordpress | {
"answer_score": 25,
"question_score": 16,
"tags": "plugins, multisite"
} |
Taxonomy slug by term ID
I'm trying to modify wp_nav_menu to display term thumbnails. To get those thumbnails I need term ID and taxonomy slug: `$thumbnailimg = get_the_term_thumbnail($term_id, '$taxonomy', 'medium');`
I managed to get term ID for it with: `$term_id = (int)$item->object_id;`
But now I need to check if that object is a term AND what custom taxonomy that term belongs to (I have 2 of them).
Can anyone help me to solve this problem? :) | For a menu object `$item`:
* `$item->object` stores the object the menu item refers to, e.g. 'post', 'page', 'my-cpt', or 'my-taxonomy' (the post type name, or the taxonomy name)
* `$item->type` stores what 'type' of object is it, either: 'post_type' or 'taxonomy'.
For custom links, these are both custom | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "custom taxonomy, menus, terms"
} |
Forcing WP to embedd a video when using a shortcode
With the following shortcode for YouTube videos, how can I make it such that WordPress still automatically embeds the video for me?
<? /** YouTube shortcode, usage: [youtube align="alignleft" id="123456789" ] */
function shortcode_youtube($atts) {
extract(shortcode_atts(array(
"id" => '',
"align" => 'aligncenter'
), $atts));
return '<div class="'.$align.'">
}
add_shortcode("youtube", "shortcode_youtube");
?>
What it currently does, is display the url of the video. What I want is it to embed the video (like it would do if I just pasted the video's url into the wp editor). | There may be a more graceful way to do this, but it works:
function shortcode_youtube($atts) {
extract(shortcode_atts(array(
"id" => '',
"align" => 'aligncenter'
), $atts));
global $wp_embed;
$content = '[embed] . $id . '[/embed]';
$embed = $wp_embed->run_shortcode( $content );
return '<div class="'.$align.'">' . $embed . '</div>';
}
add_shortcode("youtube", "shortcode_youtube"); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "shortcode, youtube"
} |
Get RSS feed about plugin new update
I would like to know if there is a way to get a rss feed when one of the plugin of my website is available.
Indeed, I need to manage updates of some website, but I don't want to lose my time connecting on those websites to see if there are really some plugin updates... So getting a rss feed would be perfect.
Is it possible to do it?
Thank you very much. | If your main goal is to get notified in new plugin updates, then you can easily accomplish this with a plugin. Update Notifier. < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rss, updates"
} |
Upgrade wordpress core programmatically with PHP
**What I want to do**
I want to upgrade Wordpress programmatically to a later version. That I want to do with PHP, lets say from <
I already know how to get the URL of the latest version so I don't having any problem with checking for versions or finding the right URL.
**Answers I want**
* A link to a tutorial of how this is done.
* A plugin that does this and not so much more.
* A hint to the functions that I need to use.
**Answers I don't want**
* The way to do it with SVN or subversion.
* Answers containing Wordpress MU.
* How to manually doing this.
* How to do this with other code than PHP. | > A hint to the functions that I need to use.
I'm not sure why you'll want to mimic WP's default behavior, but most of the update logic lies on `wp-admin/update-core.php`
Check for `do_core_upgrade()`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -2,
"tags": "php, upgrade"
} |
How to reset a custom theme
After making a lot of little changes to the current custom theme [ [zeeBizzCard]]( I'm using, I want to reset it back to it's original style. Being new to WP, I didn't make a backup of the default theme and can not find a quick and easy method of reseting the theme.
Have I missed something, or is there no "reset" options for downloaded themes?
Thanks | If you look into the file `includes/admin/theme-admin.php` you’ll see that the theme’s options are stored in `'themezee_options'`. You can either delete these options per database manager or per a plugin.
If you aren’t familiar with database operations, copy the following code into a PHP file, install it as plugin and activate it once. Then deactivate it immediately.
/**
* Plugin Name: Reset zeeBizzCard options
*/
register_activation_hook( __FILE__, 'reset_zeebizzcard_options' );
function reset_zeebizzcard_options()
{
delete_option( 'themezee_options' );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "themes, admin"
} |
Maintaining plugin addons while upgrading
I'm developing a freemium wordpress plugin where "skins" will be available for purchase to customize the appearance of the plugin.
If I commit an update to my plugin, it sounds like the contents of the "skins" folder inside of my plugin would be removed (since the skins don't come bundled with the core plugin), and the user would lose any skins they may have purchased.
What can I do to circumvent this issue? Should I look into moving the skins folder temporarily while upgrading, or somehow utilize the database?
Thanks! | I'd suggest either using the database if possible or using a folder outside your plugin folder. A sub-folder of the `wp-content/uploads` appears to be a popular choice, as it survives updates/upgrades. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, upgrade"
} |
Create/Edit/Check cPanel Email Accounts from Wordpress
I need a plugin (or other) recommendation to allow users to create email accounts, as well as change their passwords and check their email using WordPress.
I have a multi-author baseball website and I would like to allow authors to create their own email addresses at my domain name, if they like.
That being said, I do not want to create the email addresses myself. I do not want/need to know the authors' passwords to the accounts and want them to know I respect their privacy.
Thanks. | I've successfully used this to enable users to create an email account and/or ftp account on cpanel from within a WordPress site. Good luck, and let me know how it went.
There seems to be a small bug in the latest plugin version. You can easily fix it, I've described the steps below:
1. Open your code editor
2. Open up search and replace
3. Select the plugin folder to search
4. Search the source code for `/cpanel_ops/`
5. Replace it with `/cpanel-operations/`
6. Save your changes on these files
It should say that four instances have been replaced within 3 files:
1. /cpanel_ops.php
2. /email_form.php
3. /ftp_form.php | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugin recommendation, email"
} |
Moving from one host to another - cannot access the dashboard
I'm having a problem with my WordPress installation. I'm trying to move it from one host to another (switching hosting providers for my sites). I was following the instructions given here, and everything went smoothly except for one little thing: I can no longer access the dashboard.
Similar to this (unanswered) question: moving server can not login
The site works, I can see all the posts, all the uploaded pictures, all the comments and tags - everything is there and available. I just cannot access the dashboard. Password recovery didn't help, and doesn't seem to be the problem. It doesn't complain, just clears the fields when I click "log in" and stays on the login page.
Note that the domain name doesn't change, I switched servers, but the domain remains the same.
What could be the problem, and how to solve it? | I ended up deleting that copy of the installation, and cloning my site using the manageWP plugin instead. That worked just fine. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "login, hosting, migration, wp login form"
} |
Common user login for two different wordpress installation and bbpress
I have situation, that i need common user login for
1. Blog A
2. Blog B
3. bbPress
I found the solution Single use login for two wordpress installation from Justin Tadlock Blog.
Installing two WordPress blogs with the same users
But What for bbPress ?
Is there any plugin can work for me ? Should i use wordpress multisite (i am using it)?
Thanks In Advance ! | Multisite User Management
This plugin works for me! Automatically add users to each site in your WordPress network. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, user access, bbpress"
} |
Redirecting search to specific templates with $_GET["post_type"]
I'm using `$_GET["post_type"]` to direct my search to the correct templates and have used the following:
<?php $search_refer = $_GET["post_type"];
if ($search_refer == 'news') { load_template(TEMPLATEPATH . '/search-news.php'); }
elseif ($search_refer == 'members') { load_template(TEMPLATEPATH . '/search-members.php'); }; ?>
I need to add another `elseif` to this where the search refer is news but the posts have the status "future". Is it possible to do that?
The current news search refer needs to only show posts with the status "published". | I think you need to check status in your `search-news.php` template. And if `$_GET['status']` is equal to `future`, create custom loop for it. Your `search-news.php` could look something like this:
if ( $_GET['status'] == 'future' ) :
$the_query = new WP_Query( array(
'post_type' => 'news',
'post_status' => 'future',
// else arguments ...
) );
while ( $the_query->have_posts() ) : $the_query->the_post();
// do stuff ...
endwhile;
wp_reset_postdata();
else :
// do normal news stuff ...
endif; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, search"
} |
Wordpress custom search url
I'm trying to chang my custom search url for SEO purpose. I found an article about how to change `mydomain.com/?s=query` to `mydomain.com/search/query`. However, i prefer to have a custom search url such as `mydomain.com/something/query`.
Is this achievable?
Thank you for any help! | It's easy. Just add this hook for `template_redirect` action and it will redirect your search queries to nice url:
function wpse8170_search_url_redirect() {
if ( is_search() && !empty( $_GET['s'] ) ) {
wp_redirect( home_url( "/something/" . urlencode( get_query_var( 's' ) ) ) );
exit;
}
}
add_action( 'template_redirect', 'wpse8170_search_url_redirect' );
Add to your `.htaccess` file:
# search redirect
# this will take anything in the query string, minus any extraneous values, and turn them into a clean working url
RewriteCond %{QUERY_STRING} \\?s=([^&]+) [NC]
RewriteRule ^$ /search/%1/? [NC,R,L] | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "urls, search, customization"
} |
Custom loop request based on custom field
I have many post, all categorized. So 100 post, 40 in cat=4. All those 40 post have a custom field name point with a rating in there (how many point win). Si the question How to loop through all the post, and get ONLY the post with cat=4, and sort those post base on the point score in the custom field, and display, post title, and point. So the output will look like :
* john : 134pt
* paul : 124pt
* kim : 100pt
* joe : 90 pt | See WP_Query in Codex for info on how to query on custom fields.
$args = array(
'posts_per_page' => -1,
'cat' => 4,
'meta_key' => 'point_score',
'orderby' => 'meta_value_num'
);
$points_query = new WP_Query( $args );
while( $points_query->have_posts() ):
$points_query->the_post();
the_title();
echo ' : ';
echo get_post_meta( $post->ID, 'point_score', true );
endwhile; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, loop, sort"
} |
What is the correct/safe way to delete all comments?
We've inherited a WordPress (3.3.2) site that has 13k pending comments, all of which are spam.
To delete all these comments is it sufficient and safe enough to do:
DELETE FROM wp_comments;
DELETE FROM wp_commentmeta;
...or alternatively `TRUNCATE` both tables in the database? | Yes. That will be sufficient. And I highly recommend that you activate the Akismet plugin to block spam. Probably if you think there might be any genuine comments in the 13k pending ones, then install and activate Akismet first. Then go to Comments in the Wordpress Dashboard, and click on 'Check for Spam'. It should automatically move all spam to the Spam folder. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "comments, database"
} |
What is the difference between these two methods of writing $ instead of jQuery in WordPress
What is the difference between these two methods of writing $ instead of jQuery in WordPress
(function($) {
// $ Works! You can test it with next line if you like
// console.log($);
})( jQuery );
... Which I found here
and
jQuery(function ($) {
/* You can safely use $ in this code block to reference jQuery */
});
... Which I found here | The first is a pattern called a _closure_. It's not unique to jQuery. You could just as easily write
(function(someVar) {
// Inside the closure, someVar == "test"
})("test");
Basically, you're manually passing jQuery into the closure by referencing the `jQuery` object externally and aliasing it to `$` inside the context of the closure.
The second pattern is unique to jQuery. It's one of the library's shortcuts to the DOM ready event. The following calls are all equivalent:
jQuery(document).ready(function($) {
// Use $ inside here like normal
});
jQuery.ready(function($) {
// Use $ inside here like normal
});
jQuery(function($) {
// Use $ inside here like normal
});
In all three examples, you're also passing the `jQuery` object into your function as the variable `$` so that it's available within the local scope. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "plugin development, theme development, jquery"
} |
firing function at login within class
I've got a function that I'm trying to fire at wp_signon (grabs data from a remote server and updates accordingly). I'm running the function within a class that is on a secondary file in a plugin (i.e. brought in with a require_once). For the life of me, I cannot get this function to run at all.
add_action( 'wp_signon', array(&$this, 'login_pull_updates'), 40, 3 );
function login_pull_updates() {
update_option('ap_login_run', 'YES I DID');
}
I'm using that now to just test and confirm it's running at all, and it won't fire. Any ideas? | wp_signon doesn't exist (at least according to < but I tried tossing this into a fresh theme and it seems to work:
class TestThing {
function __construct() {
add_action( 'wp_login', array($this, 'login_pull_updates') );
}
function login_pull_updates($login, &$user) {
update_option('ap_login_run', 'YES I DID');
}
}
$test = new TestThing(); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp admin, login"
} |
Post/Page Preview Template
Is there a way to have a custom template php file that is only used for previews instead of it using the single.php file? This way the user knows they are in preview mode? | You could use the conditional is_preview() to add a bit of extra content.
For instance, you could put this at the very top of your single.php right after the header is called - or you could put it in your header.php file if you want it shown at the very top of the page:
<?php
if ( is_preview() ) { ?>
<div>You're viewing a preview</div>
<?php } ?>
Hope this helps, best of luck! | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 7,
"tags": "posts, customization, templates, previews"
} |
Check if Currently on Static Posts Page
I'm developing a website using WordPress 3.3.2 and have the Front Page and Posts Page set to use static pages. I'm trying to show different menus using `wp_nav_menu()` for the static front page and static posts page respectively.
I was able to find `is_front_page()` to check for the front page, however after hours of banging my head against the WordPress Codex and checking the mighty Google I can't find a comparable function or method to check if the user is currently on the static posts page.
Has anyone run into this? Any help would be greatly appreciated! | There are two options:
// If the current page is the blog posts index,
// but is NOT the site front page
if ( is_home() && ! is_front_page() )
or
// If the current page has the ID of the
// page assigned to display the blog posts index
if ( is_page( get_option( 'page_for_posts' ) ) | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "posts"
} |
merging terms programmatically while maintaining the count
This question is all about finding out the best way to handle merging similar terms.
Let's say you have 10 posts tagged as `Barack Obama` and 20 posts tagged as `Obama`. and you want to group them all under `Barack Obama` and get 30 posts for it and get rid of the tag `Obama`.
Surely, there will be some changes to the wp_terms, wp_term_taxonomy, wp_term_relationships. But in doing so, which APIs should be used and under which order so that while one tag is being gotten rid of, all the posts associated with it will be tagged as the other one. | The plugin Term Management Tools will allow you to merge tags. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "tags, terms"
} |
If statement to check if post has image
I have the following code. When There is only one image in the backend, the second image shows up with a little question mark instead of nothing. I am looking for a way to check if the image exists first and if so run the code and if not don't.
<?php $image = wp_get_attachment_image_src(get_field('post_image1'), 'thumbnail'); ?>
<img src="<?php echo $image[0]; ?>" alt="<?php get_the_title(get_field('post_image1')) ?>" />
<?php $image = wp_get_attachment_image_src(get_field('post_image2'), 'thumbnail'); ?>
<img src="<?php echo $image[0]; ?>" alt="<?php get_the_title(get_field('post_image2')) ?>" /> | wp_get_attachment_image_src will return false if there is no image. So before you echo the image add `if ($image !=false)` | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "posts, images"
} |
All pages after level 1 showing 404 after WordPress migration plugin - how to fix?
I am in the process of moving my blog away from GoDaddy (yey!) to HostGator. I used the migration plugin on GoDaddy tat created the gz archive of the database, and I copied all my files over to the new host.
My front page displays fine, but it is everything after this that shows 404 - ie. ~/profile-who-am-i/, and other category pages.
I suspect some rewriting rule isn't being followed after installing everything on HostGator and would like some assistance on how to fix this.
Thanks. | Go to Dashboard > Settings > Permalink Settings. However it's set, change it to something else, one of the other formats. I had an issue moving, same symptom as you described, and this fixed it.
You can also see this help guide on Go Daddy for help with this issue. (this edit added by another user. NP, but details almost identical. /JTP) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "404 error, rewrite rules, migration"
} |
Set front page option using custom fields?
Hello wordpress gurus!
I want to be able to set the frontpage via a custom field.
So for example, in the new page area in the wordpress admin there is a custom field that displays "Set as frontage", instead of the user going to the Settings > Reading settings and setting the front page there they can do it via the new page.
I'm familiar with metaboxes and some coding but i'm not sure how i could implement this.
I also found this article on setting the front page programatically:
<
Its just the matter of putting it together with the custom field.
Help appreciated. Thanks | You can do it by updating 2 options.
<?php
//This could be page or posts.
update_option('show_on_front', '<posts/page>');
//This one sets the page you want on front, won't work if the above option is set to 'posts'.
update_option('page_on_front', '<id of the page you want to set as front page>');
?>
Though I cannot guarantee if this is safe and whether it will override the settings saved from the backend! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field, metabox, options, frontpage"
} |
Why are my comments closed?
I have a simple site with a few pages plus a blog. For some reason, the blog posts state **comments are closed** and I can't figure out why. I want to open the comments on all blog posts (and not offer comments on pages).
In the "edit post" screen, the "Comments" section just states "No comments yet." but doesn't offer any way to turn them on.
In settings>discussion, I have these:
> ON Comment author must fill out name and e-mail
> OFF Users must be registered and logged in to comment
> OFF Automatically close comments on articles older than (14) days
> ON Enable threaded (nested) comments levels (5) deep
> ON Break comments into pages with (50) top level comments per page and ...
>
> OFF Before a comment appears An administrator must always approve the comment
> ON Comment author must have a previously approved comment
>
> ON Hold a comment in the queue if it contains (1) or more links. | Have you tried go to "Posts" and checked the box next to the title and in the dropdown "Buld Actions" choose Edit and then apply, Comments and in the dropdown "Allow".
And also have added the screen in the post edit area on the tab in the header called "Screen Options" and checked the field called: Discussion?
And in settings->Discussion have you enabled "Allow people to post comments on new articles"? | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "comments"
} |
Sort a custom post type array numerically
We've set up drop down lists to allow people to filter posts based on custom post types.
In order to populate the drop down list I am using:
<?php $terms = get_terms("ratios");
$count = count($terms);
if ( $count > 0 ){
foreach ( $terms as $term ) {
echo "<option value='" . $term->slug . "'>" . $term->name . "</option>";
}
}?>
</select>
The slug and the name are pretty similar, so I don't mind which one we are using.
How can I list them as integers?
The site is here if you need more of an idea: < | `get_terms` function will return an array of object. Each of them has `term_id` field which contains id of a term. Just use it instead of slug and you will have what you need:
<?php $terms = get_terms("ratios");
if ( $count($terms) > 0 ){
foreach ( $terms as $term ) {
echo "<option value='" . $term->term_id . "'>" . $term->name . "</option>";
}
}?>
</select> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "array, sort, terms"
} |
Add tabindex to navmenu
I would like to submit a "tabindex" attribute in a navmenu structure. The default options do not allow me to do it. | You could write a custom walker to change the output of `wp_nav_menu()`. The walker should extend the function `start_el()` to add your attributes where you need them. Another option would be a filter on `'walker_nav_menu_start_el'`.
But be aware that `tabindex` can make a page less accessible. If don’t have an urgent problem to solve do not use `tabindex`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "menus"
} |
How can I merge two authors?
I noticed on one of my WordPress installs I have two admin authors with the same email address. Both of them have posts attributed to them. They are both for the same person, so I'd like to combine the two accounts into one. How can I do this? | Delete one account.
Upon deletion WP will prompt you with a question of whether to delete all posts by said author or attribute them to another user.
Simple as that, wanted functionality is provided by the core. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "admin, author"
} |
the_post_thumbnail with lazyload JQ plugin
I need to modify the_post_thumbnail function to run "Lazyload" on it, i think there is two solutions :
1- modify the args to be something like this
the_post_thumbnail('product', array('data-original'=>$src, 'src'=>'grey.gif'));
(((NOT WORKING!)))
2- get only the image url from the function ... i've tried alot of snippets and nothing worked for me , like this one !
$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "size" );
any ideas??
thanks | If you want to apply lazyload to each attachment image, you can just add your hoot to `wp_get_attachment_image_attributes` filter:
add_filter( 'wp_get_attachment_image_attributes', 'wpse8170_add_lazyload_to_attachment_image', 10, 2 );
function wpse8170_add_lazyload_to_attachment_image( $attr, $attachment ) {
$attr['data-original'] = $attr['src'];
$attr['src'] = 'grey.gif';
return $attr;
}
Or if you can use second approach:
$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "size" );
// add more attributes if you need
printf( '<img src="grey.gif" data-original="%s"/>', esc_url( $thumbnail_src[0] ) ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 6,
"tags": "post thumbnails"
} |
Get image from post's gallery
Is there any possibility on Wordpress to get an image from a post gallery? Images are not inserted in the post, are on it's gallery. I'm trying to do a "galleries index" page and instead having the user set a "cover image" I'd like to take any of the attached to the post as part of a gallery.
I tried the wp_get_attachment_image() with no luck, I think because it works for inserted images, not the ones on it's gallery.
Thanks in advance.
Juan.- | You can get the attached media to a post using get_children. IE: get the first attached image for post ID == 14
$args = array( 'post_mime_type' => 'image',
'numberposts' => 1,
'post_parent' => 14,
'post_type' => 'attachment' );
$first_attached_image = get_children( $args ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "posts, images, gallery"
} |
get_var is neither a string, integer, or array ...?
$vote_count = $wpdb->get_var($wpdb->prepare("SELECT votes FROM wp_mytable WHERE product = %s AND
company = %s", $product, $company));
if(is_int($vote_count)){
$html = '<a href="#" class="vote_for_doc">
Vote here</a> (<span class="vote-count">' . $vote_count . '</span> Votes for ' . $product . ' and ' . $company . ')';
}else{
if(is_string($vote_count)){
$html = '$vote_count is a string in the database<p>' . print_r($vote_count);
}if(is_array($vote_count)){
$html = '$vote_count is an array in the database<p>' . print_r($vote_count);
}else{
$html = '$vote_count is not a string or an integer<p>' . print_r($vote_count);
}
}
And my output:
> $vote_count is not a string or an integer
>
> 1 | var_dump($vote_count) should tell you what type $vote_count is. Probably you're getting NULL. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, mysql, wpdb"
} |
What is the right way to make custom main page?
I am making a custom theme and I want the main page to be a gallery, not a blog,
is it right to change `index.php` to a gallery page (content wise) or should I use another page? | There are definately a few ways of achieving this functionality. I assume by "main page" you mean the home page...
a. Create a new page called "home" b. In your site settings change your homepage to point to the "page" home, rather then grabbing your 10 newest posts. c. Now you have a page hook which you can build a custom template for in one of two ways.
1.) Use wordpress "custom page templates" to create a new template and apply to the new "home" page in "edit page" <
OR...
2.) You can simply create a new file called "page-home.php" (ensuring the slug of your new home page is "home") and WP will use this page template instead....
Solution 2 is more streamlined for progamming if your clients don't need to apply templates themselves.
Hope that's helpful to you | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development"
} |
Feeds not working on my wordpress site
I just made my wordpress website live finally and now trying to set up the RSS. I came across a couple tutorials saying that you have to go to www.yoursite.com/feed copy the link and place it into the URL area in your feedburner account. However what happens if nothing shows up when you go to www.yoursite.com/feed ? It says the URL does not exist, however I have a blog on the site.
Is it because my permalinks aren't set to a custom permalink? | The `/feed` slug only works if you've turned on pretty permalinks. From the looks of things, you haven't.
Instead, you can use this url:
Once you turn on pretty permalinks, that URL will _still_ work, but the prettyier < will also work. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "rss, feedburner"
} |
How can I attach images to a post from the media library?
Currently, there is no way to do this in a vanilla Wordpress install. Is there a way to retroactively attach an image from the Library to a post?
EDIT: Ah, let me clarify — when editing a post, and clicking the "Insert Media" button, I see no way to add past media. I can insert it into the post, but not add it to the post gallery. | This is not something that is currently supported in WordPress. There's some discussion about it here: <
One plugin which does enable this functionality is:
<
This plugin does a few extra things, but one option it provides is that after clicking "upload/insert" and going to the media library tab, you can tick check boxes beside images and choose to attach them to the current post.
There's also an old thread on WordPress support forums which pertains to adding a small bit of code to your functions.php file to enable this functionality but I think that only works within the Media Library section, not when in the Upload/Insert thickbox, so the above plugin might be your best bet.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "plugins, images, media library"
} |
term_exists returns NULL
According to the codex ( < ), term_exists returns some mixed results but not NULL. In my case, I'm getting NULL, what am I doing wrong?
In this particular example 'Videos' term does not exist under category. Shouldn't it be returning a false or 0? Why NULL?
$term_exists_results = term_exists($term, 'category');
echo "<p>term_exists('{$term}', 'category')?";
echo "<blockquote>";
var_dump ($term_exists_results);
echo "</blockquote>";
/*
outputs...
Taxonomy: [category Term: [Videos]
term_exists('Videos', 'category')?
NULL
*/ | It can return null in some cases if you look at the code: <
The method get_var returns null if no result is found. If you check with "==" and not "===" that should work with false or 0. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "api, terms"
} |
Two Custom Post Types, Share Two Taxonomies
I have two custom post types
* Hotels
* Things to do
And I have two taxonomies
* Activities
* Regions
So when a user sees a **Hotel** (custom post): the user can then see
* the region it's in
* what activities they can do.
_And viceversa as well_
When the user sees **Things To Do** , he can see in which **Region** it is and what **Hotels** have the same type of **Activity** nearby.
The problem if I use two custom post type and create a taxonomy for it, I have no way of discerning each taxonomy related to a custom post:
> Example: **Hotels** in X **Region**
I would get both the **Hotels** and **Things to do** custom post, within that taxonomy.
* * *
It's basically the same issue as this question (which doesn't have any great answer). | I prefer set different taxonomies with distinct slug for them, I'm dealing with a project alike yours:
* Hotels (taxonomy is _continent-hotels_ ) values: Europe, Asia etc
* Places (taxonomy is _continent-places_ ) values: Europe, Asia etc
Even if both itens share same taxonomy and value, is easier to link the content than filter in frontend. Maybe I'm wrong but things seems tidier this way.
You can use non-hierarchical taxonomies for especific items such Hotels (romantic, economic, etc). | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "custom post types, custom taxonomy"
} |
Top toolbar is not showing in wordpress admin panel
Today I came over a very interesting and confusing problem. I developed a wordpress website in my localhost and it run perfectly. But when I moved that site in my server I saw a strange thing. When I logged in my admin panel (..wp-admin/index.php) my toolbar isn't showing up and any widgets that were showing fine in the dashboard in my localhost are gone! And also the screen option and help buttons aren't working. And when I hover over my menu items in the admin menu section sub menus were shown in my localhost, but here nothing. but everything works fine when i'm not in the index.php page. any idea from the experts? | I've a solution of my problem. I used chrome developer tool to find out the differences between the sites in my server and in my localhost. While inspecting the source I found following error-
<div class="inside">
<br>
<b>Fatal error</b>: Out of memory (allocated 43778048) (tried to allocate 132605 bytes) in <b>/home/easyitca/public_html/samples/movierez/wp-includes/wp-db.php</b> on line <b>787</b><br>
</div>
and then i googled for the memory allocation problem. Then I added following in my wp-config.php file as suggested-
define('WP_MEMORY_LIMIT', '64M');
but still it was saying same problem. And then I increased the memory limit from 64M to 128M and it worked!
define('WP_MEMORY_LIMIT', '128M'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "admin, dashboard"
} |
Banner in Wordpress
I'm trying to add an ad banner to my wordpress homepage (in the header) plus a separate ad banner for all other pages (in the header). I did get the banner up for just the homepage but I'm trying to figure the code to complete this issue.
`<?php if ( is_home() ) { ?><div id="banner">my content</div><?php } ?>`
How can I get another ad banner on all other pages/posts? Thanks. | What about
<?php if ( is_home() ) { ?><div id="banner">my content</div><?php } else { ?><div id="banner">not-home banner/div><?php } ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "headers"
} |
Determining Author post count
This is more of an efficiency question as the following code does do what I want.
$user_name = get_the_authour;
$query = new WP_Query('author_name=JustinH');
$author_post_count = $query->post_count;
if ($author_post_count >= jwh_option('post_count_set') {
$post_status = 'publish';
}else{
$post_status = 'pending';
}
That query pulls back all the user meta and all the data for their posts. Is there a more precise way to get to:
$query->post_count; | This thread on the wordpress codex shows how you can scope your SQL query:
$author_post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $$username->ID . "' AND post_type = 'post' AND post_status = 'publish'"); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query"
} |
force enqueue script to be first in order of prominence
I have a few scripts which are being enqueued,
the problem is that I want to force the order of prominece to which these scripts are loaded. There is one in particular which is loaded from a plugin before the theme ones which requires jquery however the plugin does not require jquery (bad dev on the plugin but I'd rather not touch 3rd party code for futureproofing reasons)
is there some way to mess with the enqueue order at runtime?
Thanks very much | You just need to enqueue your scripts before plugin does it. You can do it by setting priority to 0 for your hook. For example, do the following:
add_filter( 'wp_enqueue_scripts', 'wpse8170_enqueue_my_scripts', 0 );
// or if you enqueue your scripts on init action
// add_action( 'init', 'wpse8170_enqueue_my_scripts', 0 );
function wpse8170_enqueue_my_scripts() {
wp_enqueue_script( 'myscript', ' array( 'jquery' ) );
// my else scripts go here...
}
Setting up priority for your hooks will put it to the beginning of calling queue and your scripts will be added first. | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 9,
"tags": "plugins, jquery, javascript, wp enqueue script, wp head"
} |
wordpress theme option in other templates
I am using word press theme option panel and using those in my header.php without any issues, code as follows...
<?php
// loading theme options. used in header.php
global $options;
foreach ($options as $value) {
if (get_settings( $value['id'] ) === FALSE) {
$$value['id'] = $value['std'];
} else {
$$value['id'] = get_settings( $value['id'] );
}
}
?>
<?php echo $aagt_fb_url; ?> //loads fb url
But if i use `<?php echo $aagt_fb_url; ?>` in index.php it doesn't work, can you please help me to resolve this issue. thanks. | If you are using some custom global theme options, I’d set them in `functions.php`. Then you access them from any template if you declare them `global` first.
// functions.php
<?php
$aagt_fb_url = 'foo';
-
// template file like header.php, index.php, etc.
<?php
global $aagt_fb_url;
echo $aagt_fb_url; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme options, options"
} |
Custom row action on custom posts list page causes a wp_die?
The scenario is this:
I have a CPT called Job. I've set custom row actions for this CPT, and most of them are linked to external or custom settings pages. They work fine.
Now I've set a new row action, called as 'mark-special', and I've set the href for the link as the same posts list page with my own params as:
`edit.php?post_type=job&action=mark-special&job_id=123&_wpnonce=<custom nonce>`
I'm handling the action in a function hooked with `init`.
The problem is, when I click this link, it `wp_die`s with a message: `Are you sure you want to do this?`. But the function works as I want it to, and the CPT is set as special.
Any way I can solve this? | Found the issue. I have used `action` as a url arg, which WP uses for all its actions such as `approve_comment`, `trash_post` etc. Changed it to a custom word and my code worked like a charm! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "hacks, row actions"
} |
Add script into front from my plugin
I have a WordPress plugin, and I must load scripts from my plugin to the front of the site.
class My_Plugin {
function __construct()
{
add_action('admin_menu', array(&$this, 'add_submenu'));
add_action('admin_init', array(&$this, 'admin_init'))
}
function load_my_scripts(){
wp_enqueue_script('script', 'js/myscript.js');
}
I would like to load my script, so using the right hook which will be able to add the script into all the page of the site.
I've already tried with
add_action('wp_head', array(&$this, 'load_my_scripts'));
add_action('init', array(&$this, 'load_my_scripts'));
etc, ... but I don't find any solution... Could you help me please ? | Use `wp_enqueue_scripts` and `admin_enqueue_scripts` actions to enqueue your scripts:
// for front end
add_action('wp_enqueue_scripts', array(&$this, 'load_my_scripts'));
// for back end
add_action('admin_enqueue_scripts', array(&$this, 'load_my_scripts'));
Also pay attention that it is bad practice to load your scripts on all pages of the site. Load your script only if need be:
// ...
function load_my_scripts() {
if ( $some_condition ) {
wp_enqueue_script('script', 'js/myscript.js');
}
}
// ... | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugins, front end, scripts"
} |
How should I store global information such as a phone number so that it is editable through the CMS?
Right now I have a p element in header.php containing the address and phone number my client wishes to use for contact info. How can I set this up so that it is editable through the WP admin area so that my client can easily change this in the future? | Store it in your theme options. Read the series of articles called The Complete Guide To The WordPress Settings API. Spare no effort to read it, especially 4th article about Theme Options. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "theme development, customization, globals"
} |
How can I add custom text styles to the visual text editor?
By default an author can select from Paragraph, Address, Preformatted, Heading 1, etc..
As an example I'd like the author to have the ability to visually wrap selected text in a tag, without ever seeing the tag.
Is TinyMCE Advanced the only/best way to go? | Assuming that you are using WP 3.2+ and an up-to-date theme, the editor-style.css file should contain the styles for the editor. If you don't have one, just create it in the same place as style.css The style appear in the Styles dropdown not the paragraph type dropdown that you referenced in the question. This does indeed mean that you need to expand the button list using TineMCE advanced or one of the similar plugins (or you can do the configuration yourself in TinyMCE but it seems hardly worth it really).
You can also include all of the styles from your actual theme with:
@import url("style.css");
This makes ALL of the styles available which may be rather overkill & may sometimes make the editor unusable because of style clashes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, formatting, css"
} |
Why is querying posts messing up my pages?
I am working on a theme at the moment and I have set up a post template.
This post template is linked to some custom post types.
When I query_posts for my post type on the actual post template itself it makes the content disappear for some reason? Is there something I am missing here?
Thanks, Mark
My loop is as follows:
<?php
$query = 'posts_per_page=10&post_type=articles';
$queryObject = new WP_Query($query);
// The Loop...
if ($queryObject->have_posts()) {
while ($queryObject->have_posts()) {
$queryObject->the_post(); the_title(); the_content();
}
}
?> | use `wp_reset_query` after your loop to restore the global post data for the main loop. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, query posts, get posts"
} |
Organize uploaded media files
I have a blog with all media stored in a folder called **upload** (organize media was disabled), I've activate it to organize new uploads by date. **But how can i organize old files?**
I want this because i need to migrate the site to a Wordpress MU site, and i need to have files organizated. | Thans but I've found the solution, what it need to do is to edit the site **(Network -> Sites -> Edit -> Settings )** and change the following parameters:
Uploads Use Yearmonth Folders 0
Upload Path wp-content/blogs.dir/1/uploads
Fileupload Url | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "multisite, uploads, media"
} |
Show min and max taxonomy values
I'm trying to get the min and max values from a taxonomy, but my code is returning all taxonomies:
function get_years ($taxonomies, $args){
$hlterms = get_terms($taxonomies, $args);
foreach($hlterms as $term){
$term_taxonomy = $term->year;
$output .= $term->name;
} return $output;
}
$taxonomies = array ('year');
$args = array ('hide_empty'=>true);
$year = get_years($taxonomies, $args);
echo min(array($year));
What I'm doing wrong?
Thanks! Daniel | Not sure but try this:
function get_years ($taxonomies, $args){
$output = array();
$hlterms = get_terms($taxonomies, $args);
foreach($hlterms as $term){
$term_taxonomy = $term->year;
array_push($output, $term->name);
} return $output;
}
$taxonomies = array ('year');
$args = array ('hide_empty'=>true);
$year = get_years($taxonomies, $args);
echo min($year); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "taxonomy"
} |
when does output of get_user_count turns into an array?
**question**
WHEN does the integer output of get_user_count() turns into an array ?
**background**
The function get_user_count() in ms-functions.php returns an integer (it calls get_site_option('user_count')
The function wp_version_check() in update.php stores this integer in $user_count on line 55
Directly after that on line 73 it calls this integer with $user_count['total_users']
**reason for asking**
On my network admin pages I get the error:
_`Warning: Illegal string offset 'total_users' in /opt/htdocs/html/wp-includes/update.php on line 75`_
So I need to understand where I need to look (probably something I did somewhere)
see also: < | Via:
* <
* <
* <
I find:
1. Normally it would return an array from the cache
2. Meaning the return value of get_user_count() is different than in the php doc above it
3. But... if the cache does not contain it, it will return an integer leading (in my case) to an warning (requesting an array value from a string) BUT somehow not leading to a warning with many others (assuming they still have an array as return value, even if it does not contain a value)
I found out that when on PHP version 5.4 or later it will throw this warning. Previous versions will not throw this warning, related, see example 2 on <
It has been taken care of in 20966 | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users"
} |
Thumbnails from video posts not working after upgrading to WP 3.4
I'm using Auto Featured Image plugin to generate thumbnails for my posts. After upgrading to WP 3.4 all the posts that had videos and thumbnails generated from youtube disappeared. I found another plugin called Video Thumbnails which created the thumbnails for all video posts but now the thumbnails are not showing on the home page. Does anybody know why this is happening? The below code was used for the thumbnails:
<?php
if ( has_post_thumbnail() ) { ?>
<?php
$imgsrcparam = array(
'alt' => trim(strip_tags( $post->post_title )),
'title' => trim(strip_tags( $post->post_title )),);
$thumbID = get_the_post_thumbnail( $post->ID, array(235,235), $imgsrcparam ); ?>
<a>" class="preview"><?php echo $thumbID; ?></a>
<?php } ?> | There seems to be a solution there, though it's not perfect -it worked perfectly on one of my two sites and almost perfectly on the other...- | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "thumbnails"
} |
WordPress For Urdu Language
Can I use WordPress for Urdu Language? I want entire site to be toggled-translated in Urdu Language with one click... Is it possible to do it with some plugin or do i have to write manual codes for every component?
Thanks | WordPress is community translated. For a good number of languages, the translation is relatively complete and follows high quality standards.
The codex page on WordPress in your language reports:
> WordPress in Urdu - اردو is ongoing, but slow. Need more contributors.
So in essence: No, WP is not entirely translated to Urdu yet. You could contribute though and push things forward, if you cared.
WP uses gettext, so the translation process itself is pretty straightforward. See I18n for WordPress Developers, if you want to find out more. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "multi language, translation"
} |
Best way to develop multisite and deploy on another server?
I have no previous experience in developing multisites so be easy on me. I´m familiar with developing and launching single sites though.
I´m looking for the smoothest way to build a multisite for my client. It doesn't matter if I build locally or on a live development server. The sites will be basically the same but in different language versions, the content will also be slightly different.
I´ve been reading that it´s hard to migrate multisites to new servers because the url:s are hardcoded in the database in another way than on single installs, making search and replace much harder (or impossible?). So how should I go about then?
Develop locally and use the same url as the sites will have at launch, somehow? Use some kind of plugin to migrate multisite? I see Backupbuddy has this as a BETA feature, has anyone tried this?
Any ideas or tips on a good workflow here? | I always develop the webiste locally on my machine with the setup mydomain.dev and using svn or git to save versions of the code. The next step is to put it on a test domain like stage.mydomain.com and after that mydomain.com
I use this to change the url:s in the database: <
Its a search and replace tool that you put in your WordPress root and just run it from mydomain.dev/searchreplacedb2.php | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "multisite, customization, deployment"
} |
Update Wordpress automatically on its own
Is it possible to update Wordpress automatically so that when there's a new version of Wordpress, my installation will update itself automatically without me having to login to admin > update ? | Yes it is. Though perhaps not in the way you might be thinking.
If you check out some of the shared hosting sites, many of them have the capability to automatically update your WordPress site.
Of course, as Milo has said, it can be rather disastrous too. Especially on a site with lots of plugins installed.
So the answer is to have an **external script** that does a "manual" upgrade as per the WordPress documentation.
Firstly, the script needs to check to see if an upgrade is needed. The code is always available as " so you could write a PHP script that checked if an HTTP head request to that URL returned a 304 (not changed) or a 200. If the later, you would start the download and then ...
You _will_ want to make the script do a backup of both the site and the database _before_ doing the upgrade of course.
I would also recommend a script that can restore the site quickly. For when it all goes horribly wrong ;) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 5,
"tags": "updates, automatic updates"
} |
Why $ for jquery doesn't work?
I used the following to enqueue jquery plugins:
<?php
function my_scripts_method() {
wp_enqueue_script(
'custom functions',
get_template_directory_uri() . '/js/main.js',
array('jquery'),
'1',
true
);
wp_enqueue_script(
'dotdotdot & lightbox',
get_template_directory_uri() . '/js/plugins.js',
array('jquery'),
'1',
true
);
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
And I don't know it it's related but jquery only responds to calling `jquery(...` and not `$(...`. Why is that? | Use closure for your scripts:
(function($){
$(document).ready(function() {
// do something...
});
})(jQuery);
It is safe way to use jQuery. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "jquery"
} |
post->post_content filter
I'm trying to determine if the REGEX I'm using is incorrect -- or if I'm missing something basic here. The following:
add_filter('the_content','wpdu_image_replace');
function wpdu_image_replace($content) {
global $post;
preg_replace( '/<img.*src="(.*?)".*?>/', '<a href="\1">Image file</a>', $post->post_content );
return $content;
}
should look for any `<img>` within `post->post_content` (the post's content) and replace the entire tag with an `href` that simply links to the image file. In the end what I'm going to do with this is a bit more complex -- but I figured I'd start with the basics. Any help would be greatly appreciated. Thanks! | You use `preg_replace` function incorrectly. This function returns replaced content:
add_filter( 'the_content', 'wpdu_image_replace' );
function wpdu_image_replace( $content ) {
return preg_replace( '/<img.*?src="(.*?)".*?>/', '<a href="$1">Image file</a>', $content );
}
Also pay attention that you don't have to use global variable `$post`, because content of the post is passed to your function as first argument. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, the content, regex"
} |
Is it possible to use get_post_meta() to control HTML?
I want to hide or show an HTML widget I built depending on whether someone adds custom fields to a page via WP Admin. Is this possible?
I'd like to do this in my HTML widget template (tips.php): check if there is a value for each of the custom fields in this template. If there isn't, hide this html from view. Otherwise, if there is custom field text, show the widget.
Here's my code:
<aside id="tipContainer">
<div>
<h1><?php echo get_post_meta(get_the_id(), 'header', true); ?> </h1>
<img src="<?php bloginfo('template_url'); ?>/images/pencil_Tip.gif" alt="">
</div>
<p> <?php echo get_post_meta(get_the_id(), 'content', true); ?> </p>
Thanks in advance for any help. | You can call `get_post_meta` inside of a conditional statement and display data depending on the field value (empty or set), check the sample loop in the Codex | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field"
} |
Is there a spam comment blocker that blocks IP addresses for a limited amount of time?
I'm getting **a lot** of spam on my Wordpress blog. I'd like to cut down on the amount of comments I have to moderate. I'm looking for a plugin that does something like this: automatically marks comments as spam, and allows me to say "yes, this is spam". Once I've marked the comment as spam, block the user's IP address for X number of days. Is there a plugin out there that will do that, rather than me going through and blocking IP addresses manually? | Here's what I ended up doing. Since I received thousands of spam comments a week, I began to mark the spam comments as spam. Then, I installed WP-Ban, a simple little plugin that allows you to block IP addresses. Then, I used a simple MYSQL code block to show me all the duplicate IP addresses that were marked as spam:
SELECT `comment_author_IP`
FROM `wp_comments`
WHERE `comment_approved` = 'spam'
GROUP by `comment_author_IP`
HAVING count(*)>1
This has worked _really_ well for me and has drastically cut down on the amount of spam I receive. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin recommendation, spam"
} |
Two wordpress mu installs, same settings/plugins/themes?
I run two wordpress mu installs. They are both indentical in terms of plugins, themes and network-wide settings. The reason I run two is because they have different root-domains and different superadmins. Is it possible to simplify this setup somehow? | To a certain extent, yes.
Take a look at the WP Multi Network plugin. It allows you to have multiple, separate MU networks running off the same installation - same core, same plugins, same themes, same database. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "multisite"
} |
Wordpress : Explain Plugins & Theme string value in database
i have installed wordpress and i i have installed couple of plugins and i have got two themes already came with wordpress.
What i am asking about today is : what does the Plugins & Theme string value in database mean ?
Example [When plugins are active] , there is a value on table of :
a:3:{i:0;s:19:"akismet/akismet.php";i:1;s:9:"hello.php";i:2;s:37:"one-click-logout/one-click-logout.php";}
Example [When there are themes on the Themes folder] , there is a value on table of :
a:2:{s:12:"twentyeleven";s:7:"/themes";s:9:"twentyten";s:7:"/themes";}
I could get an explanation of what does the "a" and "i" mean from HERE , but the "s:" is what i do not know what does it mean. If i tried to change the s:37 to s:6 or any other value , the plugin becomes deactivated , so the s:37 <<< the 37 must mean something or related to the plugin somehow and that`s what i am trying to find out. | The value is a serialized php array. Further explanation is not really WordPress specific, but here you go -- the 's' is the length of the string representation of the succeeding array element (the length of the string in quotes). I.E. in
`a:2:{s:12:"twentyeleven";s:7:"/themes";s:9:"twentyten";s:7:"/themes";}`
the "12" in `s:12` represents the length of `twentyeleven`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin development, database"
} |
Hide admin toolbar based on a query string
As far as I know the showing and hiding of the admin toolbar on the front-end is a global setting, which applies to any page containing `wp_footer()`.
I want to have more specific control over the visibility admin bar—specifically, to be able to hide it based on a URL query string, such as (e.g., `?hidetoolbar` at the end of a URL).
I know that I can hide the toolbar from a specific **template file** by adding this to the top:
add_filter('show_admin_bar', '__return_false');
What hook would I use to apply the filter conditionally in **functions.php**? | You should be able to just add the filter inside of a conditional:
<?php if ($_GET['hidetoolbar'])
{
add_filter('show_admin_bar', '__return_false');
}
?>
or, since conditionally adding action handlers and filters is sometimes frowned upon, you could add your own function as a filter and then put your conditional inside that:
<?php
function my_manage_toolbar()
{
if ($_GET['hidetoolbar'])
{
return false;
}
return true;
}
add_filter('show_admin_bar', 'my_manage_toolbar');
?> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "admin, admin bar"
} |
Does WP always makes 301 redirection?
We rented a SEO specialist for our site, and he says that we have to do some changes in site structure before he starts his work.
The first is, that now most pages have 301 redirection.
For example:
* `mysite.com/2010/12/02/postname/?p=5500` is redirected to `mysite.com/2010/12/02/postname/`
* some posts are redirected from `mysite.com/2010/12/02/postname/?=12786` to `mysite.com/2010/12/02/another-postname/`
* some posts have redirection from `www.mysite.com/2010/12/02/postname/Mysite/?p=32123` to `www.mysite.com/2010/12/02/another-postname`
I would like to know:
1. Why does it happen?
2. Is it a normal WP behavior?
3. How can I change it?
4. Is it really important to avoid this for good SEO? | Yup, that is very normal.
If you don't want WP to redirect anything. Simply remove the action by adding this code into your working template functions.php file.
`remove_action( 'template_redirect', 'redirect_canonical' );`
That will deactivate the redirections, all of them. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "redirect, seo"
} |
Getting trackpacks/pingbacks for a post via wordpress?
Is there a way for someone to query the wordpress API of a blog in order to get the pingbacks/trackbacks for a post?
E.g a blog is hosted on example.com. I want to query example.com's wordpress API to get a list of its posts, and for each post I want to query it, to get a list of the trackbacks.
Is that possible? | You may be able to find that information in the blog's feed, i.e. example.com/feed/ I'm unsure if the trackback would be public, you may have to view the Comments section of the WordPress blog. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, xml rpc"
} |
Is there a default template file for child pages / subpages?
This seems like a very simple question. I'm looking for something like sub-page.php or page-child.php where I can do some different things on the child pages of my theme.
They are different enough in design and content that I'm having to use a lot of php or the CSS .page-child class to do all the dirty work. I'm looking for a simpler method.
One caveat - I would like this to happen automatically so I don't have to tell the client "make sure to always select the 'subpage' template when you create a subpage!" which is precarious.. | There is no specifica template for child pages, but you can do this pretty easily with the get_template_part() function.
First create a file called "content-child.php".
Second create a file called "content.php".
Next, inside of page.php, place this:
if( $post->post_parent !== 0 ) {
get_template_part('content', 'child');
} else {
get_template_part('content');
}
Anything that you want displayed on a child page will be placed inside of content-child.php. Anything you want displayed on non-child pages will be placed in content.php. | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 5,
"tags": "pages, page template, child pages, template hierarchy"
} |
Per theme plugins?
I'm building a plugin that heavily modifies the commenting section of a blog page. It think that I cannot do this in a way that works with all themes — some CSS has to be tweaked, depending on the particular theme in use.
I'd guess that in the future, the plugin will also store some data in the database. So I suppose it should be a plugin, not a theme. (?)
Hence these questions:
1. Is it possible to in some way indicate that a plugin works with only this and that theme?
2. And then release some fairly simlar versions of the plugin, each version tweaked for a specific group of themes?
3. Or are plugins supposed to work well with... all themes in existance?
4. Can you think of some solution other than per-theme-plugins and/or forking-and-modifing-existing-themes? Perhaps child themes? But, no, then it would not be possible for users-of-my-child-theme to create their own child themes? | There is no way to bind it to a specific theme unless you contact theme authors and they link back to you at some point (on theme activation with yellow message on the top or in their admin menu etc). As you suggested yourself, a plugin is supposed to work with any theme.
Theme and plugin markets could handle this by indicating that their plugins work with their themes only but this is a corporate restriction and cannot be applied technically.
What could be do is when you release something, you could name and describe it so it's pretty much obvious (such as here - < ). Also, in your plugin you could check for the currently activated theme (see get_current_theme ) and output some error message from within your plugin that it's inappropriate choice. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, themes, child theme"
} |
file_get_contents Not allowed in Themes?
I'm using `file_get_contents` in a theme development (in a widget of the theme). However the theme check plugin gives me following warning:
WARNING: file_get_contents was found in the file file.php possible file operations.
Line 49: $data = file_get_contents ( '
Line 62: $count= file_get_contents ( $cfile );
My question is that if it is not allowed in the themes, is there any alternative for this function which can be used? Thanks. | > `Line 49: $data = file_get_contents ( '
Don't use `file_get_contents` to download web page. WordPress has HTTP API for such needs. In your case, I would suggest you to use `wp_remote_get( ' );` function instead of `file_get_contents`.
Further reading:
1. WordPress HTTP API
2. `wp_remote_get` function. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "theme development, themes"
} |
Do all wordpress themes a similar class name for content?
I was wondering if all wordpress theme have a similar class name for the content.. For example I know the class for post/content in the twenty ten and twenty eleven is
.entry-content
if not then how would I go about referring contents for all theme using jQuery?
e.g $j('.entry-content').css('color','red');
thanks | There is no mandatory class name for posts. Many themes use the `post_class()` if that is needed but you cannot rely on it.
To change the output of `the_content()` add a filter to `'the_content'`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "posts, jquery"
} |
What hooks/filters are there to alter selected terms on post save?
Very simple, where would I hook/filter to alter the users selection of terms when they save a post (Update or Add)?
I need to hook in all instances; such as when saving a post via AJAX, saving when JavaScript is disabled and a normal POST is done and when posts are saved via quick edit. | It is always `'save_post'` (or `'wp_insert_post'` immediately after this). In `$_POST['tax_input']` you will find all the terms for all taxonomies associated with the current post.
Example:
'tax_input' =>
array (
'location' =>
array (
0 => '0',
),
),
To change the terms you have to call `wp_set_post_terms( $post_ID, $tags, $taxonomy );` manually, just changing these values will not work because they are set when the actions fire.
For an existing post that is updated you can hook into `'edit_post'` and `'post_updated'`.
Parameters for all these actions are `$post_ID, $post` in this order. For `'post_updated'` there is a small change: `$post_ID, $post_after, $post_before`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "taxonomy, filters, hooks, terms"
} |
Make 'Howdy, [name]' function as log out button
I have been customising the `admin bar` in version 3.3 to only have certain custom links with the following added to `functions.php`:
function mytheme_admin_bar_render() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu('site-name');
$wp_admin_bar->remove_menu('new-content');
$wp_admin_bar->remove_menu('updates');
$wp_admin_bar->remove_menu('comments');
$wp_admin_bar->remove_menu('edit-profile');
$wp_admin_bar->add_menu( array(
'id' => 'reports', 'title' => __( 'Reports'), 'href' => __('xyz.html'),
));
}
add_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' );
I'd now like to have the far right link that says Howdy, ..., function as a Logout button.
Does anyone have any suggestions on how achieve this? | EDIT: This is obviously not a good idea if you want to be able to update - see comments below
As this site explains, you need to replace `<?php printf(__(‘Howdy, %2$s!’), ‘profile.php’, $user_identity) ?>` in the wordpress admin with in your case the word 'logout.' Then make the url be `echo wp_logout_url();` | stackexchange-wordpress | {
"answer_score": -8,
"question_score": 4,
"tags": "admin bar"
} |
changing parent_id on post
I'm trying to change a post's parent via the wp_insert_post_data filter but I'm not having any luck. In the example below, I'm replacing any "parent" references with the id I want to set.
function my_insert_post_data($data, $postarr){
$data["post_parent"] = 123;
$postarr["parent_id"] = 123;
$postarr["post_parent"] = 123;
error_log(print_r($data,true));
error_log(print_r($postarr,true));
}
add_filter( 'wp_insert_post_data' , 'my_insert_post_data' , '99', 2 );
and when i log the objects, i see the properties have been set but that never gets written to the database. | In order to make it working you need to return updated data:
function my_insert_post_data($data, $postarr){
$data["post_parent"] = 123;
$postarr["parent_id"] = 123;
$postarr["post_parent"] = 123;
error_log(print_r($data,true));
error_log(print_r($postarr,true));
return $data;
}
add_filter( 'wp_insert_post_data' , 'my_insert_post_data' , 99, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, filters"
} |
Storage of array in settings
I'm creating a plugin that will store some simple layouts to be used in shortcodes.
The shortcode usage will be similar to `[shortcode layout="name"]`
With this mind I'll need to store each layout in the array as a key/value setup
Key = layout name
Value = layout markup
I'd like to store these in settings however I'm not sure how to go about it. How can I create a settings page that allows addition and editing. Normally my settings pages use code as follows and automatically wires into the api.
<input type="text" id="company_name" name="wpv_settings[company_name]" value="<?php echo $wpv_settings['company_name']; ?>" class="regular-text" />
However, I can't find how to go about this when the setting is an array of key/values.
Can anyone point me in the right direction of how this would be done? | Since the layout names are dynamic, perhaps it's better to store them in a numerically indexed nested array? Something like:
wpv_settings[layouts][0][name] = $key
wpv_settings[layouts][0][markup] = $value
wpv_settings[layouts][1][name] = $key
wpv_settings[layouts][1][markup] = $value
...etc? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "settings api"
} |
Where should a plugin or widget cache its results?
_Where should a plugin cache its re-usable results?_
I have read the code of several well-used Wordpress plugins, and it seems that the answer is not consistent. I have written several plugins myself, and I store things in a cache directory. But I just picked the location of the directory out of a hat, and my code creates the cache directory if it doesn't exist. This seems arbitrary.
I know there are plugins that do caching. Suppose I don't want to use a plugin. I find that relying on the filesystem to cache results is easy for maintenance, diagnostics, and performance.
Is there a good, more-or-less standard approach, or a blessed approach, to choosing a filesystem location for a cache? | > I find that relying on the filesystem to cache results is easy for maintenance, diagnostics, and performance.
Please note that this might be true in some (maybe even most) circumstances, but not **all** of them. If your code is meant for anything beyond personal usage you _don't know_ with which file system and hardware will it be used and how will it perform there.
WP is engineered to use database for storage of textual data, that is more typical and logical first choice than file system.
> Is there a good, more-or-less standard approach, or a blessed approach, to choosing a filesystem location for a cache?
`wp-content` folder is meant as a place for files uploaded or generated during operation. Plugins that use file cache should create folder for it in there. Note that WP is flexible about most of folder structure and it can be easily renamed/relocated from defaults - use appropriate functions to determine that rather than hardcode default path. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, cache"
} |
_deprecated_argument for constants
i'm working on updating a theme and previously it had used a lot of php CONSTANTS to set up some options as true or false. we're going to be updating these "decisions" to use add_theme_support() instead. is it appropriate to use the _deprecated_argument() function to tell child themers that these constants are deprecated? if not, what is the best way to trigger a deprecation warning for a constant? | Unfortunately there is no way to trigger WP deprecation warning for PHP constants.
What I can suggest - to use your constants and "theme support" options together. First for backward compatibility, second for customization facilities. Your theme will have to rely on "theme support" options only, and keep constants only for child theme.
The trick is in the way of declaration such constants. You have to define your PHP constants based on what has been added to support by theme.
After updating your theme, you need to let people know that you don't use PHP constants any more and you will remove PHP constants in further releases. You can place such information on a site via which you distribute your theme. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "deprecation"
} |
Separately formatting date elements
I am trying to achieve the following look in the time format:
!enter image description here
I have for now several issues,
First is that the month and year are not displayed at all, I use `<?php the_date('D'); ?>` `<?php the_date('M'); ?>` `<?php the_date('Y'); ?>` for start and only the day is shown,
Second - Are there WP functions I can use to
* Get the month in 3 cap letters?
* Get only 2 last digits of year?
Or I have to use my own PHP functions for that?
Also, it must be hard-coded in the theme, because otherwise it will mess up the design.
**Update**
I used `<?php echo get_the_date('M'); ?>` and I got all the times, but isn't `the_date` meant exactly for that? | I believe all the info you need is in the PHP Manual for Date/Time. Also, it is recommended that you use `get_the_date();` instead of `the_date();`
> **Get them month in 3 cap letters?**
`M` is the right format character that outputs a short textual representation of a month (3 chars). Why can't you use CSS to capitalize all the three letters? I mean, `text-transform: uppercase;` should do it.
> **Get only 2 last digits of year?**
Use the small `y`. It outputs two digit representation of a year.
**EDIT (to answer the updated question)**
The function reference for `the_date();` in codex has a **special note** that says:
> When there are multiple posts on a page published under the SAME DAY, `the_date()` only displays the date for the first post (that is, the first instance of `the_date()`). To repeat the date for posts published under the same day, you should use the Template Tag `the_time()` or `get_the_date()` (since 3.0) with a date-specific format string. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "date time, date"
} |
Custom image size vs CSS sizing
I am developing a theme which will have 2 configuration options for the slideshow in the header; a full width version and a half width version. The theme is also responsive and so I am trying to optimize it as much as possible from a speed point of view. I am trying to decide which approach is best.
1. Use `add_image_size()` to create a new image size to use for when the user selects the half width configuration
2. Use the full width images and re-size them using CSS
The advantage the new image size is that the slider images would be smaller, this is positive since the theme is to be responsive, however it means that every image in the library now will have an extra image created, even though only a small few of these images will actually be used in the slider.
Which would be the best approach, or is there anything else to consider? | The best approach is to serve the smaller image sizes, that is what matters to the end user. If you do the math on something like 5 slider images (large ones) you will see a pretty significant difference. Image sizes are in most cases the largest request.
The downside is simply having more storage on your server, but that doesn't effect the end-user nor is it expensive. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "theme development, css, images, slideshow, responsive"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.