INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Does WordPress send data about your blog back to Automattic or somewhere else?
> **Possible Duplicate:**
> Does WordPress send data about your blog to WordPress.org or Automattic?
I've recently heard someone say that WordPress sends data about your blog to home (where ever that is). Is that true? and if so what is sent away or where in the code can I see what's exchanged? | This is true to a degree. They probably do this for a few reasons but most likely to help monitor bugs and things like that in regards to future improvements and updates. Nothing malicious to worry about! They need to keep track of versioning especially so that you can be notified of updates to WordPress itself as well as themes and plugins.
Your WordPress installation syncs up every 12 hours. A few things they keep track of: wordpress version, php version, locale, whether multisite is enabled, etc.
You can get a much better understanding of what they are tracking if you check out `includes/update.php` in your WordPress installation as everything is outlined in that file. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
How to restrict a plugin from certain pages without editing its core
I've run into a problem using two different twitter plugins. One is for login and one is for displaying a twitter stream. The issue is they both use Oauth so I get a re-declare error when trying to login on my custom login template. Since I only use the twitter stream plugin on profiles I'd like to limit it's functions use purely to the profile but without actually changing the plugins core code. Possible? | I would approach as follows:
1. Identify all the action/filter hooks in the plugin
2. Identify all scripts/styles being enqueued.
3. Create a function that removes the actions/filters based on the page using `remove_action`, `remove_filter`, `wp_deregister_style`, `wp_deregister_script`
You could use something like the following:
function foo_disable_plugin(){
if(is_page('PAGE_TITLE OR ID')){
remove_filter('the_content', 'PLUGIN_FILTER_NAME');
remove_action('wp_head', 'PLUGIN_ACTION_NAME');
wp_deregister_script('PLUGIN_SCRIPT_NAME');
}
}
add_action('template_redirect', 'foo_disable_plugin', 999999999);
If this doesn't work, you're probably going to have to make one of the plugin's classes pluggable.
if(!class_exists('CLASS_NAME')){
//Class goes here
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, content restriction"
} |
remove page template from dropdown?
I created a page template, uploaded it, but then changed the template name later.
/*
Template Name: New Name
*/
Now, the new template name is showing up on the Page dropdown, but so is the old template name. How can I delete the old one from the list?? | Just remove the old file from your theme's directory. That list of templates is generated from the files present in your theme, so you probably have two files. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "page template"
} |
Hook when new CPT published AND postmeta inserted
I would like to know if there is a hook that fires when a new CPT is published and its postmeta has been inserted.
I was using publish_mycpt but found that the postmeta wasn't being saved at that point. I would like my hook to run only for this custom post type, not for all posts.
The function I will be calling via the action hook is also used by a scheduled cron job, so it's not only called when a new post is published via the administration interface, not sure if this is important or not. | I believe you can do it using the save_post hook, than do a conditional check for the post's post-type and the value of its post meta.
add_action( 'save_post', 'do_some_function');
function do_some_function($post_id) {
global $post;
$post_type_as_taxonomy = array('cpt-1','cpt-2'); // this is your hooked custom post types
$post = get_post( $post_id );
if(in_array($post->post_type, $post_type_as_taxonomy) && $post->post_status=='publish'){ // check if the post is hooked & published
$my_meta = get_post_meta($post_id, 'my-meta', true); // check if it has a post meta with the ket 'my-meta'
if($my_meta){
// do your hook function here
}
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "hooks"
} |
echo post-permalink without http and www
I have this line …
<div class="permalink"><?php the_permalink(); ?></div>
and the result on my page looks like this …
I guess it could also look like this …
However I'd like to have just `mysite.com/whatever/post-or-so` without the ` or `www` in front of it.
What is the best and easiest way to do so?
Don't get me wrong, this has nothing todo with rewriting permalinks or whatsoever. Just a simple echo of `the_permalink()` on my page that is not handled as link but as normal text. And in this case I would like to get rid of the http or www. | use `get_permalink` instead of `the_permalink` and manipulate it however you'd like via php. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "permalinks, urls, customization"
} |
changing theme folder name breaks menus - twentyeleven
I needed to change the twentyeleven theme folder name, so I activated the default theme, changed the twentyeleven folder name to X, then reactivated it. Everything worked except the menus were all in the wrong places. I figured out they needed to be redefined in Menus>Theme Locations. But now, there's an extra sitemap listing in the footer.. I didn't put it there and can't figure out how to get rid of it. It's listing out the sitemap in ul tags, twice. Any suggesions? | Try going to **Dashboard -> Appearance -> Menus** and re-applying your custom menus to the appropriate Theme locations.
By changing the directory name, you've impacted the `theme_mods`, including custom menus. To WordPress, **`/wp-content/themes/twentyeleven/style.css`** and **`/wp-content/themes/X/style.css`** are two different Themes, _even if all the files are the same_. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "menus"
} |
Search functionality with multiple categories
Good day fine wordpress gurus,
I'm having a tough time writing a function that handles the search in a couple of user-selected categories. The way I'm presenting the categories is through the old get_categories method and I'm iterating through the array in order to build a category tree with checkboxes (client requirement).
So what I need is a hint of how to get the search in such a way that it includes the search term and the cat_ID's that the user selected in order to bring the relevant results.
PS: I already checked out Wordpress Multiple Category Search this link, and I didn't find anything useful. so please help. | Sounds like something Relevanssi could handle. With Relevanssi, you'd have the checkboxes to choose the categories. Then, you'd write a function to hook on 'relevanssi_modify_wp_query' filter, where you'd read the checkboxes and convert them to a comma-separated list of category ID's. That you would store in $wp_query->query_vars['cats'] and hey presto, Relevanssi gives you relevant results in those categories.
I think the same idea might work with default search, actually, but instead of 'cats' you'd use 'cat' and instead of 'relevanssi_modify_wp_query' you'd need another way to modify the $wp_query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, search"
} |
adding a custom css class to post
essentially I need to be able to add a class to a post when it show in the list (say index.php) so when in the back end you can say oneCol, twoCol, threeCol and it will then output this within the loop post class.
This is to enable a tighter control of the layout. using this line of code for the output?
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>
Thanks in advance! | > ### Note -
>
> I recommend using the hook suggested by _@Chip Bennett_ in another answer
>
> **Here's the modified version of that filter -**
>
>
> function wpse_filter_post_class( $classes ) {
> $my_post_class = get_post_meta($post->ID, "your_meta_name");
>
> if( $my_post_class != '' )
> $classes[] = $my_post_class;
>
> return $classes;
> }
> add_filter( 'post_class', 'wpse_filter_post_class' );
>
You can setup a Custom fileds for that - See usage, then use `get_post_meta()` function to fetch it and show where you want
**Example -**
<?php echo get_post_meta($post->ID, "your_meta_name", true)?>
This will output the class name set in the `meta_key`.
**OR ( Update #1 ) -** Pass the variable into `Post Class`
<?php $my_class = get_post_meta($post->ID, "your_meta_name") ?>
<div id="post-<?php the_ID(); ?>" <?php post_class( $my_class ); ?>> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, customization, css, post class"
} |
Query Custom Post Type by Tag
Kinda confused on this.. hoping someone can help.
I have custom post type named "Providers" that I want to pull entries from that are tagged "highlighted". I enabled tag support on the custom post type and then tried using tag=highlighted and tag_id=15 in a new query but it's just showing the hello world post.
Here is the gist:
< | Ahhh.. not sure why I didn't think to use tax_query. A friend figured it out. Gist is updated. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, php, wp query, loop, tags"
} |
Feed only showing 1 result?
Any ideas? It seems my feed is only showing one post, although I made several today.
< | The first time I went to it I got this error "XML parsing failed: syntax error (Line: 77, Character: 8)"
Check the feed validator for more help < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "rss, feed"
} |
Wordpress do_shortcode first iteration
I've created a recursive shortcode that looks like this.
[tabs]
[tab state="active"]Home[/tab]
[tab]About[/tab]
[tab]Contact[/tab]
[/tabs]
[tabcontent]
[tabpane]Content 1[/tabpane]
[tabpane]Content 2[/tabpane]
[tabpane]Content 3[/tabpane]
[/tabcontent]
It is working, but I would like to remove the state="active" and automatically add that to the first tab, but I'm not sure how to tell which iteration my do_shortcode is on?
**Update:** What would be even better is if I could keep a count while iterating through the do_shortcode so I could add attributes like id="tab1", id="tab2". | Figured out both issues. You can keep a count and find out when you are on the first iteration in the same go.
static $count;
if(!$count) {
$count = 1;
$state = ' active';
} else {
$count++;
$state = '';
}
From the PHP Manual. "A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope."
This code sets a static variable within the recursive function, in this case a function called by do_shortcode(). This lets you keep a count going so if you wanted to have id's like #tab-1, #tab-2 you could easily do so. With this code you can also tell when the first iteration happens. I set a $state variable and give it an active css class. Since I'm appending it to a class attribute already I've only got active, but you could also pass the whole thing if you only had one class like class="active" for example. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
Should multi-language site using multi-site architecture have default language in base site?
I am setting up a multi-language site using wordpress multi-site and wanted some feedback on the best approach/best practice.
I will have the following languages: en, sa, de, ru. en is default.
Should the domain.org by default be English, or should domain.org redirect to domain.org/en? | Create a subdomain for each language, set the main site to English. Then use the plugin Multilingual Press to chain these subdomains together. It has an option to redirect the visitor to the correct single page too if it is translated on another subdomain (not sure if that is part of the free version).
Subdomains are slightly better than sub directories for SEO because Google will detect the correct language with … a higher probability. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "multisite, multi language"
} |
My site looks different when activating new theme
I'm working on my site ontwik.com, just created a new design and uploaded it and when I activate, it works fine for the homepage and otherpages. but the problem is when i lo gout from wordpress admin or open ontwik in a different browser the homepage looks great but the other pages using the old theme.
I tried to activate my oldest themes to see if the problem from the new theme but still there.
You can visit the site now and check for difference.
Thanks | You're using WP Super Cache; reset the cache for the problem page(s) and it should display the new design.
The reason it looks different when you're logged in is because the static pages are served to
1. Users who are not logged in.
2. Users who have not left a comment on your blog.
3. Or users who have not viewed a password protected post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
WordPress theme options vs custom post types
For dynamic content across a WordPress website, is it a better practice to create new post types for updating content or using theme options?
I personally find theme options a little more time consuming to code than registering a new post type in `functions.php` | It depends on the type of content.
Is the content dynamic, likely to change, likely to have repetitions of the same types of information, time dependent? I'll probably use a custom post type.
Is the content unlikely to change, or only needs one instance of the information set (like a logo, Google analytics code, social media usernames, etc)? Theme options.
There is another option that's sometimes viable: custom post meta-data. I'm working on a site right now where one of the pages has a list of FAQs set up in an accordion-style interface. My plan is to set up a custom meta-box specifically attached to just that page to hold the key-value pairs for the FAQs. This could be set up as a custom post type, but I'm setting it as custom post metadata. I figure this will be easier for my client, rather than having to learn, remember, and find yet another UI element. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom post types, theme options, content"
} |
Retrieving meta-box from a custom-post-type
I am trying to display data from a custom post type on my home page, for which I am using a separate template.
I'm getting a Fatal error: Call to undefined method WP_Query::have_post() when my code looks like this:
get_header(); ?>
<div class="home_main_text">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'home' ); ?>
<?php endwhile; // end of the loop. ?>
</div><!-- #primary -->
<?php
$current = date("d/m/Y");
$args = array('post_type' => 'jh_dedications');
$loop = new WP_Query($args);
while ( $loop -> have_post() ) : $loop->the_post();
the_title();
endwhile;
?> | `while ( $loop -> have_post() ) : $loop->the_post();`
Your missing an s `have_post()` should be `have_posts();`
Your title says retrieving meta-box and I am assuming you mean the post_meta. Which you use the get_post_meta() function. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, wp query, metabox"
} |
Do we have In_category like function for tags?
I have been using "if (is_single() && in_category('keyword') )" to display custom links on the sidebar. I was wondering if we have in_tag or any similar function for tags? | Here is the source of `in_category` function:
function in_category( $category, $post = null ) {
if ( empty( $category ) )
return false;
return has_term( $category, 'category', $post );
}
You see, it's actually `has_term`. This is the same as `has_category` function.
For tags, there's no `in_tag` function, but you can use `has_tag`. It has the same functionality:
has_tag( $tag, $post );
Or you can use:
has_term( $tag, 'post_tag', $post );
where `$post` can be omitted (default is current post).
They're all the same! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "tags"
} |
Slider Plugins for header
I am new at wordpress. I need one header slider plugins like this
Please suggest me plugins.
I am use "header-image-slider" but it will not display below slider of main image.
Thanks in advance | i am use this plugins for the slider thethe-image-slider.1.1.8 and it is very nice and very easy to installed.
Thanks and i hope it also help you | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugins, plugin recommendation"
} |
Check if function called by cron job
I have a function that I only want to run via a cron job. Is there a way I can check that a particular scheduled event is calling this function and not anything else? | WordPress has a constant `DOING_CRON` that helps us know we're doing the cron jobs or not. It's defined in `wp-cron.php` file.
So, you can check this constant in your code:
if ( defined( 'DOING_CRON' ) )
{
// Do something
} | stackexchange-wordpress | {
"answer_score": 28,
"question_score": 17,
"tags": "cron"
} |
Block multiple categories from Blog
I found this code on this site by AshFrame which I added to my functions PHP file and works perfectly to stop one category being displayed on my blog (I have a custom menu so have the category displayed separately)...
add_action('pre_get_posts', 'block_cat_query' );
function block_cat_query() {
global $wp_query;
if( is_home() ) {
$wp_query->query_vars['cat'] = '-98';
}
}
My question is how do I format this code to include a second category (in my case -92)? I tried duplicating the code but it generates a PHP error because you can only run the function once I think. | _cat_ takes a comma deliminated list, so '-98,-92'
Further reading < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories, blog, customization"
} |
custom post on homepage
How would I include a post from a specific category on my homepage in buddypress?
Example I have a category 'Homepage Banners' with an ID of 3.
In the admin I create a post and assign the 'Homepage Banners' category to it.
I then need this to show up on the homepage (the latest post).
I am new to WP/BP, any help appreciated.
Thanks. | You can also use a new query (with php enabled) so show a single post by ID, i.e. the post with ID 101:
<?php $my_query = new WP_Query('p=101'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_title(); ?><?php the_content(); ?></a>
<?php endwhile; ?>
This can be used multiple times inside the WP loop without conflict.
Use Exec-PHP « WordPress Plugins or others. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop, buddypress"
} |
What is the $menu parameter used of in wp_nav_menu()?
I have a theme where I register multiple menus in function.php. All menus have a unique name and a simple description (we just use the name of the theme so they all have the same desc but thats ok).
In our templates we use the following code
wp_nav_menu(array('theme_location' => 'sub_menu_manager', 'menu' => 'Manager', 'sort_column' => 'menu_order', 'container_class' => 'manager-menu', 'menu_class' => 'template-menu'));
Can someone explain what 'menu'=> 'Manager' does please? Thanks | The `menu` parameter is to get The menu that is desired and it accepts (matching in order) id, slug, name.
meaning in your case that the desired `menu` is named `Manager` but the `theme_location` parameter as the last word so if no menu is set in that location the menu will be the one named `Manager` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus"
} |
old permalinks not found
Looking through Google Webmaster Tools, I have a lot of 404s for posts with permalink structure of /%year%/%month%/%day%/%postname%/
I have since changed permalinks to /%category%/%postname%.html
I thought Wordpress could redirect old post URLs to new post URLS, but the old date based URLs are generating 404s.
My .htaccess file is writable, set to 644.
Why is this occurring? Thanks! | WordPress doesn’t catch _all_ old URLs, you have to help it. Add the following code to your .htaccess _above_ the WordPress rewrite rules:
RedirectMatch permanent /\d+/\d+/\d+/(.+)$ /?pagename=$1 | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, htaccess, 404 error"
} |
Sort post by custom field numeric value
I am trying the way to sort post from custom field numeric value.
Here is my query:
query_posts( 'cat=2684' );
how to tell to use the custom field "sort_number" value | To sort your posts by a numeric value in a custom field your query would look like this:
query_posts('cat=2684&meta_key=yourCFkey&orderby=meta_value_num'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query posts"
} |
Equal height sections in custom Headway Theme
I have this piece of code:
<section class="row row-3">
<section class="column column-1 grid-width-19 grid-left-0">
<section class="column column-2 grid-width-5 grid-left-0">
</section>
The first section of the row (column-1) will have variable height depending on the content. The second section (column-2) is the sidebar, and always has the same content (widgets) and height. I now need this sidebar (column-2)section to be the same height as the first (column-1)section.
As I'm using headway Themes, so I cannot add any div's, or ID's to the layout. I therefor don't know how to use the scripts I find on the internet.
Any help much appreciated! | We can do this without touching theme files either by using a child theme or Writing a Custom Plugin,
To include only css I'd use plugin rather than a child theme.
## Example -
<?php
/*
Plugin Name: My Styles
Description: My Custom Styles for THEME-NAME
*/
//Create a `my-style.css` in plugin folder
add_action( 'wp_enqueue_scripts', 'wpse64258_custom_styles' );
function wpse64258_custom_styles() {
wp_register_style( 'my-style', plugins_url('my-style.css', __FILE__) );
wp_enqueue_style( 'my-style' );
}
?>
> **For CSS Code read these articles -**
>
> * 4 Methods For Creating Equal Height Columns In CSS
> * Fluid Width Equal Height Columns
> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, javascript, html5"
} |
How to get single post by one author?
I just want to get the most latest posts by an author. I am using get_posts at the moment but I notice it doesn't take an author argument, so how I can I specify my author?
$args = array( 'numberposts' => '1');
$posts=get_posts( $args );
foreach($posts as $post)
{
setup_postdata($post);
//do stuff
} | `$args = array( 'author' => 1, 'numberposts' => 1 );` The author parameter isn't documented on the `get_posts()` codex page, but it does work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, wp query, author, get posts"
} |
Check if password protected post is visible
Is there anyway of checking if a password protected post is visible / not visible? I want some thing that says this;
If the post is password protected (that parts fine) and the correct password hasn't been entered, then show 'XXX', else show 'ZZZ'. | `post_password_required()`: whether post requires password and correct password has been provided.
<?php
if ( post_password_required() ) {
echo 'xxx';
} else {
echo 'zzz';
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "theme development, templates, password, template tags"
} |
Hierarchical taxonomy UI
I don't like the way the taxonomies are displayed within the Wordpress admin and was wondering if anyone knew the best way to hook in and change it. Currently if I select some terms within my post those selected terms go to the top of the list and the hierarchy is broken making it visually confusing for the user.
Please see these images for an idea of what I'm talking about
!enter image description here !enter image description here
I want to display the taxonomies exactly how they are displayed initially with just the correct terms ticked. Is there a way of doing this without having to edit the Wordpress core directly, I can't see any hooks for me to use.
Thank you for any help you can give!
Helen | There is a plugin by Scribu called Category Checklist Tree that disables this "feature". | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 11,
"tags": "custom taxonomy, hooks, terms, user interface"
} |
altering search terms
How can you filter or alter the search terms that users enter into a search field? Is there a hook available?
The idea is to use this function to filter out 2-3 letter "filler" words ("on", "and", "the", etc.)
function prepSearchStr($str){
$str=preg_replace('©[^a-zA-Z0-9]©', ' ', $str);
$str=preg_replace('©(?<=\s|^)(([a-zA-Z]{1,3})|[0-9]{1,2})(?=\s|$)©', ' ', $str); //remove smaller groups of characters
$exploded=explode(' ', $str);
$exploded=array_filter($exploded);
return implode(' ', $exploded);
} | You can use `parse_query`:
function wpa64292_parse_query( $query ) {
if( isset( $query->query_vars['s'] ) && !empty( $query->query_vars['s'] ) )
$query->set( 's', prepSearchStr( $query->query_vars['s'] ) );
}
add_action( 'parse_query', 'wpa64292_parse_query' );
Note that it won't alter the query string you see in the browser, but if you echo `get_query_var('s')` in your template you'll see it's been altered. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, search"
} |
How to remove title (home) from static page skeleton template
I am trying to remove the page title (home) from my index page. I made my home page my static page.
I am using the skeleton theme <
I'm new to wordpress so I hope I'm explaining this right. | I've never used the theme, but the code seems to show that there is an option to hide the title. Line 23 of < shows post meta for `hidetitle`. Look for a checkbox on the edit page maybe? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, title, customization"
} |
which is the best way to customize nav-menu-template.php?
I have modified the function `start_el` in `nav-menu-template.php` substituting `$item->ID` with `$item->title` so that the html `li` elements in menu have a more readable class names. In detail, I have changed the line
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
to
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->title, $item, $args );
This makes the editing of the `style.css` file for a theme easier. I wonder if it is possible to "transfer" the change from `nav-menu-template.php` to the theme (maybe `functions.php`?), so that I will not be forced to modify the file every time I upgrade WP version. | Simply add the following into your `functions.php`:
add_filters( 'nav_menu_item_id', 'wpse64308_nav_menu_item_id',10,3);
function wpse64308_nav_menu_item_id( $id, $item, $args){
return 'menu-item-'.$item->title;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, customization, menus"
} |
Editing options pages?
I'm trying to find a way of adding a single checkbox to one of the existing options pages, most likely options-reading.php programmatically. Unfortunately, I haven't found any good references on this. Any thoughts from the community? | I just did some searching and found this in the codex:
add_settings_field( 'myprefix_setting-id', 'This is the setting title', 'myprefix_setting_callback_function', 'general', 'myprefix_settings-section-name', array( 'label_for' => 'myprefix_setting-id' ) );
Here is the link to the codex <
Looks as simple as choosing the right slug like 'general' to add an option to the general settings page.
I hope this points you in the right direction. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, options"
} |
Check if a class exists within a method
I'm new to OOP and I'm writing my first plugin. I want to check if the Facebook plugin has already been activated. If so, I want to skip some code:
class MyClass {
...
function fb_js_sdk_setup() {
// Check if Facebook plugin is activated
if ( class_exists( 'Facebook_WP' ) )
return;
// Continue if Facebook plugin is not active
...
}
}
My `if (class_exists())` statement isn't working. Appreciate any advice and pointers. Thanks! | You should use `is_plugin_active()` method to check if a certain plugin is activated. The class `Facebook_WP` will still exists even you deactivate the plugin. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins, php, oop"
} |
How to get a meta value from all post
I searched for a while but I didn't find any solution. I used the functions listed here. It outputs something like this:
Array
(
[0] => 15
[1] => 30
[2] => 50
)
But I want something like this:
Array
(
[post_id_1] => 15
[post_id_2] => 30
[post_id_3] => 50
)
And this is the $wp query that is used in the function:
function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) {
global $wpdb;
if( empty( $key ) )
return;
$r = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
return $r;
} | `get_col()` function returns only one column as array. To get two column result we can use `get_results()`, Which will return an array of objects
Which further can be converted into required structure using foreach loop.
**Example -**
function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) {
global $wpdb;
if( empty( $key ) )
return;
$r = $wpdb->get_results( $wpdb->prepare( "
SELECT p.ID, pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ));
foreach ( $r as $my_r )
$metas[$my_r->ID] = $my_r->meta_value;
return $metas;
}
_( The modified version of your Example )_ | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "custom field, wp query"
} |
get_the_terms - but only show 4 Posts
I am using this code to load related posts with a custom taxonomy term slug:
<?php
global $post;
$terms = get_the_terms( $post->ID , 'topics', 'string');
$do_not_duplicate[] = $post->ID;
if(!empty($terms)){
foreach ($terms as $term) {
query_posts( array(
'topics' => $term->slug,
'showposts' => 4,
'caller_get_posts' => 1,
'post__not_in' => $do_not_duplicate ) );
if(have_posts()){
while ( have_posts() ) : the_post(); $do_not_duplicate[] = $post->ID; ?>
But I always get more than 4 posts. How can I really set this query to just 4 posts?
Thanks!
AD | You need to specify number of posts to retrieve. 'showposts' is how many to show on page, and is deprecated (use 'posts_per_page' instead)
'showposts' => 4,
'numberposts' => 4, | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query, terms"
} |
How to add admin bar only page?
I successfully managed to create admin bar item using this:
add_action('admin_bar_menu', 'toolbar_link_to_mypage', 999);
function toolbar_link_to_mypage($wp_admin_bar){
global $wp_admin_bar;
$theme_menu = array(
'id' => 'theme_page',
'title' => __('test', 'test'),
'href' => '
'meta' => array('class' => 'test')
);
$wp_admin_bar->add_node($theme_menu);
}
But I can't figure out what is the correct way to create an admin panel **OPTIONS PAGE (not sub-menu item! Two answers are about sub-menus already)** for `'href' => '',` parameter. I can't simply use `add_menu_page();` because that would attach it to left navigation as well. Any help would be great! | You have to create a new array for the new item and pass the `parent` parameter as the id of this already created item. In your case, the args array should be like this:
$args = array(
'id' => 'my-item',
'title' => 'My Item',
'href' => '#',
'parent' => 'theme_page',
'meta' => array(
'title' => __('Click Me'),
),
);
This post has a complete explanation of how and where you can add items to the admin bar and the usage of the `parent` parameter. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin menu, admin bar, add menu page, settings api"
} |
Images not being generated at correct size
I have my WordPress Media settings set like so. Based on these settings no generated large image should exceed the width of 540px.
I embed an image in a post like so. I choose "Large" as a image size, which should have a restricted width of 540px.
The end result is an image of 1024x769px. Why won't the image adhere to my Media settings? | Try uploading the image again now you've set up the media settings, this should fix it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "uploads, attachments, media, options"
} |
Pagination doesn't work for home page custom post type query
I've spent hours trying to figure this out, tried TONS of different methods and all failed in their own way.
What I'm trying to do:
Limit home page custom post types (woo_estate) to 6 and then paginate the rest.
What happens:
Not only the home page custom post types don't get limited, no pagination is added.
Current template code that loads in home page:
< | I had a double query and that was why nothing worked.
var_dump($wp_query);
helped me find out about this fact.
A lot of the codes I used should have worked in the first place.
Once the double query was removed, everything worked again. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, pagination"
} |
WPAlchemy MediaAccess "Add Media" button opens new page instead of pop up
I'm using WPAlchemy for a custom meta box that lets you upload media. however the "Add Media" button is taking me to the "add media files to your computer..." as a new page (as if it were just a regular link) instead of opening as a pop-up on the same page. I tested my media upload button in a regular post situation and it popped up. | Okay, I solved it (again, cause this happened before but I forgot the solution!)....
This was for a custom post type and I hadn't added a support that involved uploading something. So, I added "thumbnail" to the list of supports...
'supports' => array('title','author','thumbnail')
for my custom post and that did the trick! It's a weird little glitch. I hope to | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "wpalchemy"
} |
Output menu navigation in php file
I have a WordPress site which generates a menu at the top of the page with this:
<?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?>
This line is located somewhere in a file called `header.php`.
(Location in wp-admin is: `Appearance -> Editor -> Templates -> Header (header.php)`
What i need to do is use the line i gave earlier:
<?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?>
In a separate php file. So that when i navigate to: `
That it only outputs the menu. No doctype or anything.
What steps do i have to take for this?
Thanks in advance. | You would require the path to `wp-blog-header.php` to access WordPress functionality in a standalone PHP file. So your `justthemenu.php` file should contain the following code.
<?php
require('/wp-blog-header.php');
wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) );
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "menus, templates"
} |
which is the function that removes accented vowels?
Which is the function WP uses to convert words like "voilà" and "novità" to "voila" and "novita" in category slug? Can I recall it in my theme? | If you simply want to covert accented words you can use remove_accents()
If you want it converted in a slug like format you can use sanitize_title() | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "functions, themes, slug"
} |
Making someone a WordPress administrator using PhpMyAdmin
After database problems on my provider side, I had to reset my admin user password. But then this user was not an admin anymore. In PhpMyAdmin I see that it has a user_status value of 0. How can I make this user an amin in WP dashboard ? | You actually want to look in the wp_usermeta table. Once in there, look for the entry that has '`wp_user_level`' in it's 'meta_key' column and has the matching 'user_id' that you would like to update. Then change that 'meta_value' to 9 or 10.
It is also required to update the '`wp_capabilities`' meta_key value to '`a:1:{s:13:"administrator";s:1:"1";}`'
Link to current documentation:
< | stackexchange-wordpress | {
"answer_score": 20,
"question_score": 12,
"tags": "phpmyadmin"
} |
How to solve the fopen error?
I recently updated xampp to 1.8 and enabled xdebug. I'm not sure if this is the reason for this error message which I didn't see before:
Warning: fopen( in C:\xampp\htdocs\wodpress\wp-includes\class-http.php on line 923
Maybe I did something wrong at server configure. but there isn't really anything more than enable xdebug. Need help! | That's a warning, not an error. Turn off the PHP display_errors configuration directive. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "debug, internal server error"
} |
How to log database changes during an upgrade?
I have Wordpress installed in a classic LAMP configuration. Is there any way to, in a protected environment (like staging), automatically log all database changes (i.e. drop indexes or alter tables) done by a Wordpress upgrade process? | Why would you need to log them? They're defined in the code itself.
Look at wp-admin/includes/upgrade.php. Every version that changes the DB has a function defined that does the job. The changes made for version 3.4 are defined in the upgrade_340() function. The changes made for 3.3 are defined in the upgrade_330() function. And so on. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "database, upgrade"
} |
Remove link on full-size images
Is there a way to remove the link on full size images in posts/pages?
I still would like to have it for the other smaller sizes. Since the full size image is already full size, it seems unnecessary to link to itself. | If you're adding the full size image from the Post Editor, when you select the image from the media manager pop-up box, you'll click the button that says "None" under the Link URL field.
That would be impossibly messy to control programatically. Well, maybe not impossible, but probably something that you would just hack with jQuery or something. (Find all full size images and remove the A tag sort of thing.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, images"
} |
Loop to display random posts only if a custom field matches category
Working on a website and need loop that will show posts ONLY if custom field value is equal to the current category name.
I have category 'fun' and custom field 'genre'. I would like to show on custom archive page only posts that are selected to be under category 'fun' AND at the same time if the value in custom field 'genre' is 'fun'. Order I prefer is most visited posts first at the top - if possible. | Something like this should be the query you want to run, it adds a condition to the page query that requires the value in "meta_field" to equal the current category's title.
global $wp_query;
$args = array('meta_query' => array(
array(
'key' => 'meta_field',
'value' => single_cat_title("", false),
'compare' => '='
)
)
);
query_posts(array_merge($wp_query->query, $args));
// The Loop Goes Here // | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom field, loop, query"
} |
how to edit title of bulk posts?
I have got hundreds of posts published but with inappropriate titles. I want to edit/updates titles. I have those all titles in a .txt file which I want to have them on the posts. If there is any solution?? I want the fastest way. It's also so hard for me to copy/past each title to the post. I want one-click method. I have heard on some sites that it can done by exporting all posts to .csv file which can be then edited in excel to change titles and then imported to the site. but again I guess the problem is still there in excel I have to edit each column which is again a very tedious. I wish if someone could refer me wordpress plugins or any kinda excel bot which can make my work done.
Thanks. | It depends how you produce the titles of the posts but something like:
1. Load the posts into wordpress
2. Update wp_posts using mysql
That's how I do bulk editing and it works very well. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "bulk"
} |
Custom Post Type URL doesn't work anymore
Suddenly one of my custom post types stopped working properly. More precisely, I have a custom post type called Apps where I have a few posts. Everything was working properly until I've created a new taxonomy using a plugin, then I've imported about 2-300 terms using an array in `functions.php` and then I've created a custom template for that taxonomy. Right after, the Apps posts couldn't be accessed anymore - even if nothing changed to them, the URL doesn't work, I get a Page Not Found error.
I reverted back to the original settings - delete the new taxonomy and terms, disable plugin, but I still get a 'page not found' error when I try to access the Apps posts.
You can see the behavior on this website. | Have you tried to update your Permalink Settings? That might sort it out. Btw. how did you named your CPT? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy"
} |
How do I copy a wordpress database?
I'm trying to migrate my wordpress site from an old host to a new host. The Wordpress Codex says "you can move by just copying your files and database." Copying the files is easy enough, but how do I copy my database? I'm sure I'm just not looking in the right places, but I can't find any documentation on this anywhere. | The same WordPress Codex has a page for backing up your database with phpmyadmin; see <
You must export and import the database itself - and not do a posts export from the dashboard - to retain all settings, image URLs, etc.
Either use phpmyadmin in your host control panel, or you can use it as a plugin called Portable phpmyadmin: <
But if you use the plugin, you may have to try an older version, as the newer alpha version doesn't work on some web hosts due to host restrictions.
And, if you are changing domains as well as hosts, you need to correctly change URLs in the database. interconnectit.com WordPress Serialized PHP Search Replace Tool | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "database, hosting"
} |
Show widget when not using SSL
My wordpress site supports http and https. What I want to do is to add a widget when surfing over http that says something like "Surf this site secure" to show the visitor that I also have a secured version.
I don't want to force them to surf over SSL because I'm using a type of certificate that's not supported on Windows XP.
Now how can I do this? | WordPress has built-in function for this purpose - is_ssl(). <
So, you should edit this widget and put something like
if ( is_ssl() ) {
} else {
echo 'you should use ssl';
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "widgets, ssl"
} |
WooCommerce store with ~30,000 products
I'm investigating WooCommerce as a potential e-commerce solution, however my immediate concern (which I haven't been able to find information on) is the number of products.
The proposed store needs the ability to house ~30,000 different products.
* Is there any technical limitation on the number of products that WooCommerce can handle?
* Would the limit simply be the same as the number of posts I could safely/practically handle in WordPress?
* Are there other issues that would make managing something like this _just a bad idea_? (experiences with WooCommerce) | I hate to mention this on Wordpress.Stackexchange, but I would go with using Magento in place of Wordpress. I love Wordpress and use it on almost every website that I build, but it was not specifically made for e-commerce. Magento handles just about everything better in regards to e-commerce.
I only tend to use Wordpress for e-commerce when the products and store are fairly simple. Magento will take more work to build the site initially, but I believe it would give you the best results with the number of products that you have. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 9,
"tags": "plugins"
} |
Problem using $var for shortcode attr value
I am trying to pass a variable value to a shortcode attribute. I can't get it to work.
Is the following supposed to work, or must values be literal?
$mycat = 'books';
$myshortcode = '[products category="'.$mycat .'"]';
echo do_shortcode($myshortcode);
The above outputs nothing. If I replace it with
$myshortcode = '[products category="books"]';
echo do_shortcode($myshortcode);
Then it produces the expected result.
I'm placing this code in a 'Custom Code Block' in the HeadWay Theme's Visual editor. I'm trying to find out if the problem I have has to do with the way HeadWay parses the content of the custom code block, or if it is indeed not possible to construct a string for use with `do_shortcode()` like this. | After more probing I found out, that the problem must be with the way HeadWay is parsing the content of the custom code block.
I still don't understand it exactly, but changing the code from this:
$mycat = 'books';
$myshortcode = '[products category="'.$mycat .'"]';
echo do_shortcode($myshortcode);
to this
$mycat = 'books';
$myshortcode = 'products category="'.$mycat .'"';
$myshortcode = '[' . $myshortcode . ']';
echo do_shortcode($myshortcode);
made it work... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, shortcode"
} |
Specific php document for a page
I'm Doing a site with some content that can be updated by Wordpress, but, It would be a lot times if I could write a php document for one page and other php document for another page, Like front-page.php. Is it somehow possible?
Thanks a lot in advance. | I think you are looking for 'page templates'.
Try out the codex:
Page Templates
Page templates allow you to completely change the look of separate pages on your website and still allow dynamic content to be updated by Wordpress. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "php"
} |
Show shortcode without executing it
I am trying to display code in my WordPress page and it isn't working. Everything I read says that you should be able to just use `pre` tag with code tag and it would be good but when I try to display a shortcode, it renders the shortcode rather than displaying the code.
The codex says that using `pre` and code would work but it isn't for me. Has anyone had this issue? Am I missing something in `functions.php` that makes this work? | To display a shortcode instead of rendering it you have two options:
1. Write `[[shortcode]]`. WordPress will show this as `[shortcode]`.
2. Escape the `[`, write it as as `[` or `[`. | stackexchange-wordpress | {
"answer_score": 30,
"question_score": 20,
"tags": "shortcode"
} |
Applying post title filter: Last Viewed Posts + qTranslate
I'm using Last Viewed Posts (LVP) plugin on a qTranslate-enabled website. LVP shows post titles in both languages. I found this hint: titles in recent posts appear together in all languages with qtranslate
But not sure how to apply this filter. Relevant code in LVP:
foreach ($zg_post_IDs as $value) { // Do output as long there are posts
global $wpdb;
$zg_get_title = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE ID = '$value+0' LIMIT 1");
foreach($zg_get_title as $zg_title_out) {
echo "<a href=\"". get_permalink($value+0) . "\" title=\"". $zg_title_out->post_title . "\">". $zg_title_out->post_title . "</a>, \n"; // Output link and title
}
Instead of `echo $post->post_title;` it has `$zg_title_out->post_title`.
Replacing the whole zg string with `apply_filters('the_title',$post->post_title)` didn't work. | **Solution -**
take out:
`foreach($zg_get_title as $zg_title_out) { echo "<a href=\"". get_permalink($value+0) . "\" title=\"". $zg_title_out->post_title . "\">". $zg_title_out->post_title . "</a>, \n"; // Output link and title`
insert:
`foreach($zg_get_title as $post) { echo "<a href=\"". get_permalink($value+0) . "\" title=\"". $post->post_title . "\">". apply_filters('the_title',$post->post_title) . "</a>; \n"; // Output link and title`
`$zg_title_out` was replaced with `$post`,
and `$zg_title_out->post_title` was replaced with `$post->post_title` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin qtranslate"
} |
Defining different theme for Blog posts page
So, I'm using my wordpress with a static front page and then I have Blog link that opens the blog posts.
My question is, how can I apply a different template/styling only to that area? | Refer to the Template Hierarchy in Codex.
If you have assigned a static front page, the template that will take priority for that page is `front-page.php`, and the template for the posts (blog) page is `home.php`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, theme options, blog page"
} |
How can I add a button to quicktags-toolbar?
I would like to add a button to this toolbar, right of "fullscreen":
!enter image description here
The button should add this: „“
If text is selected, it should get around the text, like this: „selected text“
How can I add such a button to the ed_toolbar (class: quicktags-toolbar)? | Try adding the following code in your function.php
add_action( 'admin_footer-post-new.php', 'wpse_64665_add_quick_tag' );
add_action( 'admin_footer-post.php', 'wpse_64665_add_quick_tag' );
function wpse_64665_add_quick_tag() { ?>
<script type="text/javascript">
edButtons[edButtons.length] = new edButton( '„“', '„“', '„', '“', '' );
</script><?php
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "customization"
} |
Do wp-cron scheduled tasks run asynchronously?
I have a task scheduled to run daily using wp-cron. The task takes over a minute to run (between downloading and parsing a very large file with cURL). According to the WP documentation,
> "The action will trigger when someone visits your WordPress site, if the scheduled time has passed."
Could this "someone" have to wait the full minute for my script to run while trying to access my site, or are wp-cron tasks asynchronous? | No, the WP-Cron tasks run asynchronously from the viewing user. They should not see any delay.
Although if your task takes more than a minute, it may never finish since most hosts are setup to kill PHP processes after 30 seconds. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "wp cron"
} |
Custom form on front page redirects on error page
I've created a form in a wordpress page (it's hardcoded in it's template.) This form redirects on the same page as it's on. This form also verifies the data right there, in the template file.
If I put this form on any page, it works. But on the front page, when I submit it, I get a page, with the default template, with only "There has been an error." in it's contents.
So how can I make that form work everywhere? How can I use POST data returned by my form on the front page? | Seems my form was using some value from the namespace of wordpress. If this problem happens to you, check what id/names you give to your inputs. If it's too general, it might conflict. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "forms"
} |
Does WordPress limit the length of slug names for Post Meta or Terms?
The WordPress Codex states the the Post Type Names and Taxonomy Names have a limit to the slug name.
* Register Post Type \-- max. 20 characters, can not contain capital letters or spaces
* Register Taxonomy \-- The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces) and not more than 32 characters long (database structure restriction).
However, the WordPress Codex doesn't state whether or not Post Meta or Terms have a limit to the slug name.
* Add Post Meta \-- No slug limit?
* Insert Term \-- No slug limit?
Can this be confirmed? Is there no slug name limit for Post meta or Terms? | The `meta_key` field for the `wp_postmeta` table is set as `varchar` type entries with a length of 255 characters. Seems pretty lengthy. It's `meta_value` partner parameter is set as `longtext` type.
As for the term length, both name and slug are set as `varchar` with a length of 200 characters each in the `wp_terms` table. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, custom taxonomy, post meta, terms, slug"
} |
Custom image size mixes width and height in output
I want to use a couple of custom image sizes for a site that I'm developing. When I output the images I sometimes do not get the correct width size because it is mixed up with the height size. It guess it has something to do with how I declare the image sizes in the functions file.
functions.php
add_image_size( 'small', 145, 999 );
add_image_size( 'medium', 300, 999 );
add_image_size( 'large', 455, 999 );
add_image_size( 'tablet', 1024, 9999 );
$image = wp_get_attachment_image_src(get_field('custom-field'), 'medium');
print_r($image);
gives me
Array
(
[0] =>
[1] => 225
[2] => 300
[3] => 1
)
Notice the width size is no. 2 in the array, when it usually is 1. Is the output order different if the image is taller then wider? The "errors" that I get are all from vertical images. | The "medium" and "large" are not custom image sizes - they are already part of the core WordPress media sizes and they should be handled via the "settings" -> "media" options page in wp-admin.
Give your custom image sizes a different and more unique name (reserved are thumbnail, medium, large, full) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "thumbnails, images"
} |
GUID not updated on import
I've exported data from my dev server and imported it to my prod server.
One template is listing child pages and uses `$page->guid` to get link to page.
The problem is that this link still points to my internal dev server.
Has anyone else had similar problems? And if yes, how do I solve it without having to edit my DB directly? | The GUID is not an URL. Use `get_permalink()` to get the correct URLs.
Just ignore the GUID. It is – as the name says – an identifier. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "import, export, guids"
} |
Replace the slug of parent pages with #
I'm creating a Wordpress site with a Superfish CSS3 / Jquery dropdown menu, complete with hoverIntent as displayed here:
<
As far as I can see, this menu works well on mobile devices, because the link values refer to the same page, like `#a`, so that clicking a link does not cause the page to reload.
Please bear with me. I know that the right way would be to replace the dropdown menu entirely (with a select box or some other tool), but I need to have the exact same experience as on a desktop (long story).
My question is: how can I replace the href value of parent pages, with an internal link like `#a`?
My guess would be that doing this via jQuery would be the best solution. What are your views on this and could someone please provide a practical answer? Thanks in advance. | In my experience, Superfish actually does not rely on in-page links in order to show the submenus on touch devices (although admittedly I'm basing this solely on iOS devices).
Simply tap once on a top-level menu item and its submenu should show. A subsequent tap on the same top-level menu item would cause the browser to load that link. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, dropdown, mobile, customization"
} |
Can is_page() be combined with a switch control structure?
I'm using an if/else control structure to add class attributes to tags. Could I use a switch control structure instead and if so, how? If not, is there a better way to do this than what I'm doing?
<div <?php if (is_page( 'project' )) { echo 'class="project"'; }
elseif (is_page('home')) {echo 'class="home"'; }
elseif (is_page('contact')) {echo 'class="contact"'; }
?>>
</div> | While Ben's answer is basically correct, is_page also checks to make sure that the query is indeed a Page and not something else with the same post_name.
So to be 100% accurate, you could do something like this:
if ( is_page() ) { // only do this for actual pages
$page_obj = get_queried_object();
switch ( $page_obj->post_name ) {
// same switch as Ben's answer
}
} else {
// not a page
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php"
} |
How to manipulate "add media" pop-up
Is there any way to add your own button next to "insert into post" button on the "add media" pop-up? I would like the button to add my own shortcode tags around the inserted image.
The desired result:
[myshortcode]<a href="link"><img scr="img.jpg" /></a>[/myshortcode]
instead of just:
<a href="link"><img scr="img.jpg" /></a> | There's no easy way to add a new button at present, however the "image_send_to_editor" filter will let you modify the HTML that is returned for the post insertion. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "theme development, media"
} |
How to make global post work with custom post type?
I was wondering to know if it's possible to use global posts with custom_types. I was working with this function:
global $post;
$myposts = get_posts('numberposts=4&offset=1& category=3,4');
foreach($myposts as $post) :
setup_postdata($post); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Visualizza <?php the_title(); ?>"><img src="<?php echo get_option('home'); ?>/wp-content/uploads/posthumb/<?php $values = get_post_custom_values("Image"); echo $values[0]; ?>" alt="<?php the_title(); ?>" /></a>
<?php endforeach;
As soon as I've moved the post from the standard articles type to a new custom post type, this stopped working. The category is still the same. Can I get it work again in any kind of way?
Thank you very much for your reply. | By default `get_posts()` uses a default post type of `post`.
If you want to select from a CPT then you need this:
$myposts = get_posts('numberposts=4&offset=1&category=3,4&post_type=YOUr_CPT_HERE'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, globals"
} |
Providing a function to override the default query
In a plugin, I want to provide a function for users to set the default query in their templates, so they can use some custom loops. What would be the best way of doing it?
I imagine something like this:
my_plugin_set_query();
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
... iteration through a predefined post set ...
}
} | I did this, and it's working, but I'm not sure if it's the best way of doing it:
function get_override_query() {
$posts = get_posts_from_some_custom_method();
$query = new WP_Query();
$query->current_post = -1;
$query->post_count = count( $posts );
$query->posts = $posts;
return $query;
}
function override_query() {
global $wp_query;
$query = get_override_query();
$wp_query = $query;
}
Then, I can also iterate through posts without changing the default query, like:
$query = get_override_query();
while ( $query->has_posts() ) {
$query->the_post();
...
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query"
} |
Loading post comments after clicking a button
Is it possible to load site comments on-demand instead of having them always display at the bottom of the post? Like by clicking on `Load Comments...`.
You can check **labnol.org**. They are using Disqus comment system which loads by clicking.
How could I achieve that? | You could try an easy jQuery approach of hiding the comments div and inserting a button to make it appear.
Instructions:
In your functions.php file of your theme, place this line of code to ensure that jQuery has been included to run the code:
wp_enqueue_script('jquery');
Then you could add this function to place the javascript code into the footer of each of your webpages:
function your_hidden_comments(){ ?>
<script type="text/javascript" defer="defer">
var comment_div = jQuery('#comments');
if(comment_div[0]){
jQuery('<button id="show_comments">Show Comments</button>').insertBefore(comment_div);
comment_div.hide();
jQuery('#show_comments').on('click',function(){ comment_div.fadeIn('slow'); jQuery('#show_comments').fadeOut('slow'); });
}
</script>
<?php }
add_action('wp_footer', 'your_hidden_comments');
I hope that helps; comment back if there is any trouble with this. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments"
} |
unregistered user can write in blog page - possible? how to?
I'm working on a site wherein the owner wants people(potential real estate clients) to be able to write their home-owning hopes, dreams, desires, etc. I'm thinking something similar to the functionality of comments, like a live-feed testimonials page?
My question is how do I facilitate this? I'm not too concerned with spam right now, just want to know how to/if it's possible.
Thanks. | This plugin allows posts from the front end: <
I have tested it and it worked fine, however, it is basic in that you can get the post title, content, category, tags using this, but if you want to add custom fields or anything more complex you may find a hand made solution works better such as this: <
Good luck!
* * *
Just re-read your question and it sounds like another option might be to use the comments functionality as you've suggested but you could create a custom page template where the comments were the main focus of the page, that would probably be an easier option than having users submit their comments as posts. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, comments, blog"
} |
UTF8 Encoding problems when exporting posts
I have a Wordpress installation with MySQL encoded as utf8_general_ci. I'm trying to export it using wordpress' export tool, but the result XML breaks some special characters such as "é", "ê", etc turning them into "é" for example.
The XML file is being downloaded into a Windows machine and scp'ed into a Linux. In both platforms the encode is off.
I checked the resulting xml with "file" and it´s telling me it is a UTF8 file.
What am I missing?
Thanks! | The file is likely correct, but the program that you're viewing it in is probably interpreting it with ISO-8859-1 / latin1 encoding.
The `é` pairing is something I have often seen when viewing a UTF-8 encoded `é` in latin1.
Be sure that the program you are viewing the file in is set to view in UTF-8 encoding. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "export, encoding"
} |
Users managed to register on website with no register button?
Due to recent spam, I wanted to stop registration on my website for a while.
But doing so meant the registration page would redirect to the homepage, which was bad for SEO.
So I left the registration page there, removed the 'register' submit button and put in a little message telling people to contact me if they wanted to be registered manually.
1 day later, I have another 5 users who somehow managed to register! All of these are spam users.
How did they do this?
I removed the 'register' submit button on the register page so did they manage to make their own submit button? (editing the webpage on their end)
Also if you go to mysite.com/wp-register.php or /wp-admin/ it asks for a password (.htpasswd protected).
The actual register page is located at: /wp-login.php?action=register (This is a custom page that matches my theme btw)
What do you think it is? I can private message you the website if you like.
Thank you! | One could easily submit the form on the page by adding a submit button to the DOM through javascript. I would suggest a redirect from the registration page to some other page without a form submission. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "users, user registration"
} |
How to change option recently_edited?
WP recently_edited option can be very useful - it tracks last 5 files that you've made changes to. Only problem is - well, that's all, 5 files.
What if I've been made numerous changes to Wordpress theme files by using default WP admin editor?
It would be helpfull if I had list of, say last 20 files edited and time when that happened.
**Do anyone know where is stored function or some else mechanism that allow only 5 item to reside into array of recently_edited WP option?**
I've tried with wp-admin/includes/schema.php and wp-includes/option.php where it, as I tohught, should be - no results. | The function is `update_recently_edited` in `wp-admin/includes/misc.php`. unfortunately it is fixed at 5:
function update_recently_edited( $file ) {
$oldfiles = (array) get_option( 'recently_edited' );
if ( $oldfiles ) {
$oldfiles = array_reverse( $oldfiles );
$oldfiles[] = $file;
$oldfiles = array_reverse( $oldfiles );
$oldfiles = array_unique( $oldfiles );
if ( 5 < count( $oldfiles ))
array_pop( $oldfiles );
} else {
$oldfiles[] = $file;
}
update_option( 'recently_edited', $oldfiles );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "database, options"
} |
Pagination stops at page 6
The loop below works fine, apart from the fact that the pagination will always stop on page 6. No matter what arguments i specify, it will never show more than 6 pages.
Does anyone know why?
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$idxargs = array(
'posts_per_page' => '1',
'paged' => $paged,
);
$idxloop = new WP_Query( $idxargs );
?>
<?php if ($idxloop->have_posts()) : while ( $idxloop->have_posts() ) : $idxloop->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>
<?php next_posts_link( __( 'Next') ); ?>
<?php previous_posts_link( __( 'Prev' ) ); ?>
<?php endif; ?>
<?php wp_reset_query(); ?> | Trying to use pagination from a different query is always fraught with potential disaster. `next_posts_link` accepts a second argument, `$max_pages`, which may solve your issue if you pass it properly:
next_posts_link( __( 'Next'), $idxloop->max_num_pages );
However, the _real_ answer to this question is to adjust your query _before_ the template. Adjusting the default query via a new `WP_Query` or by using `query_posts` is quite simply _doing it wrong_ , despite the millions of examples on the web you will see that do exactly that.
The preferred method for this is using a `pre_get_posts` action along with a conditional check to apply it to the specific type of query you want to adjust:
function wpa64918_homepage_posts_per_page( $query ) {
if ( $query->is_home() && $query->is_main_query() )
$query->set( 'posts_per_page', 1 );
}
add_action( 'pre_get_posts', 'wpa64918_homepage_posts_per_page', 1 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "wp query, loop, pagination"
} |
How to get_posts having post thumbnail?
I have following code:
$posts = get_posts(array(
"meta_key" => "special",
"meta_value" => "surprise",
// "has_post_thumbnail" => true, // how to do that?
));
What should I do to select posts having post thumbnails? | The thumbnail is stored as a meta with a key of `_thumbnail_id`, so that could be used to find posts that have thumbnails. Something like this:
$query = new WP_Query(array(
'meta_query' => array( array(
'key' => '_thumbnail_id',
'value' => '0',
'compare' => '>=',
)
)
)); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "post thumbnails, get posts"
} |
Settings API in Multisite - Missing update message
When I use the settings API in a multisite installation and the options page sits at the network level, posting the options to `options.php` does not work, because the administration page sits at `wp-admin/network` and WP expects the page to be at `wp-admin`.
I added a function that checks whether this WP installation is a multsite installation (via the constant) and if it is, it changes the form's action value to `../option.php`. This saves the options OK, but the default message "Settings saved." is missing (however, the query string does include `settings-updated=true`).
Any thoughts on how to get the message to appear? | For network option pages the correct form action URL is:
wp-admin/network/edit.php?action=your_option_name
Then you have to register a callback:
add_action(
'network_admin_edit_your_option_name',
'your_save_network_options_function'
);
In that callback function inspect the `$_POST` data, prepare the values, then save them:
update_site_option( $this->option_name, $this->option_values );
And then you have to create the redirect without further help:
// redirect to settings page in network
wp_redirect(
add_query_arg(
array( 'page' => 'your_options_page_slug', 'updated' => 'true' ),
(is_multisite() ? network_admin_url( 'admin.php' ) : admin_url( 'admin.php' ))
)
);
exit;
On the options page check `$_GET['updated']`, and add an admin notice if you found that parameter. | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 9,
"tags": "multisite, settings api"
} |
Multiple Email Addresses, One User
I'm trying to allow a user to have multiple email addresses associated with their account. `update_user_meta()` will not work because it will overwrite the current email. `add_user_meta()` wouldn't work either because it would duplicate the entry, even if it is the same email address.. Any ideas? | You can use `update_user_meta()` and `add_user_meta()`, just store all the email addresses in an array in a new field. If you have a requirement, such as preventing duplicates, run a validation function that checks for that before updating the database. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "user meta"
} |
Customize edit.php Pages listing in dashboard to show only pages with a particular template applied?
The question says it all, I think. I'd like to create a new submenu page using edit.php which will only display pages which use a certain template file (or files).
Possible? | Try this:
<?php
// add submenu page
add_action('admin_menu', 'add_template_submenu');
function add_template_submenu()
{
add_pages_page( 'My Template', 'My Template', 'edit_pages', 'edit.php?post_type=page&template=your-template-file.php');
}
// check for the template name passed in $_GET and add it to the query
add_filter('parse_query', 'filter_pages');
function filter_pages($query)
{
global $typenow, $pagenow;
if ($pagenow == 'edit.php' && $typenow == 'page' && $_GET['template'])
{
$query->query_vars['meta_key'] = '_wp_page_template';
$query->query_vars['meta_value'] = $_GET['template'];
}
return $query;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "page template"
} |
Numbers of new post since the last visit of user
I need to count the number of new post since the last visit of the user on my blog, is it possible?
Thanks to all for your help! | i think it is possible to get what you want by
Store the last date time a user login as a user meta
Use the usermeta to get posts published after the date - time uring $wpdb | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "posts"
} |
How can I compare publish and update dates for a single post?
In my theme, I'd like to display the publish date and (only) if the post was updated after the publish date, also display the updated date. The code in my theme now looks like this:
*/ stuff above here to display publish date, then do this stuff to see if updated */
if ( get_the_date() != get_the_modified_date() )
{
printf( __( '<br>Updated: <time class="entry-date" datetime="%1$s">%2$s</time>', 'splatone' ),
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() )
);
}
If the post was published and updated on the same day, I'd rather not show the updated line, but it currently is. How can I compare the dates so that I only get it if the date has changed and not just the time? | get_the_date() and get_modified_date() don't return time values: so, if you change your conditional statement to the below, it should work:
if ( get_the_modified_date() > get_the_date() )
{
...
}
Now if the updated date is greater than the original publish date(by one day), the if statement is true. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, date time, date"
} |
Select posts that match multiple category names, must match all categories listed
I need to search for posts that belong to multiple categories, but they must match all categories listed, as in if I list category names 'japanese' and 'dessert' the matching posts need to be in both the 'japanese' and 'dessert categories.
Is there something like `category__and` for category names? I am using a wordpress multi instance and my category ID numbers vary between my test and production environments, hence I cannot use `category__and`. | Well... you could grab category names ID using `get_the_category` function(Wordpress Codex).
$names = {"japanese", "dessert"};
$categories = get_the_category();
if($categories){
foreach($categories as $category){
if( in_array($category->cat_name, $names) ) array_push($ids, $category->term_id);
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, wp query, customization"
} |
product export and import using xml
I am use eCommerce plugins for the eCommerce support in wordpress
I am export my all product using `Tools->export` from my ` wordpress site and i am try to import in my wordpress another site like `
and it is not give any error but not display product main image.
I am try to debug the code and i found the problem in xml attribute name like
<wp:postmeta>
<wp:meta_key>_wpsc_product_metadata</wp:meta_key>
<wp:meta_value>dtails</wp:meta_value>
</wp:postmeta>
and
<wp:postmeta>
<wp:meta_key>_thumbnail_id</wp:meta_key>
<wp:meta_value>253</wp:meta_value>
</wp:postmeta>
i am not understood how can i change this two attribute value
please help me
thanks in advance | When you're exporting from a localhost installation, the other installation cannot import images because it technically needs to be 'online' for the new installation to download the images off the older one.
The easiest thing to do would be to migrate the old site to an online installation. You can read about how to move Wordpress in the Codex. After it's online, the new localhost installation and other installations will be able to properly import the older site including its images. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "import, migration, e commerce, plugin wp e commerce, export"
} |
Updating URLs in many posts
I copied my WP content to a new install on a different server, so now my uploaded PDF documents have the old URL. Is there a simple way to fix that in all my posts at once, perhaps with SQL or some plugin ? | Use the script found here:
<
Because WordPress serializes some urls in option and meta tables a simple replace won't do.
A siple replace will break your data.
This script will preserve your data and replace it with a new url.
I use it al least twice a month. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "urls"
} |
How to get themes from wordpress.com per SVN?
I'm running wordpress on my own host and would like to install the Ideation and Intent theme. I couldn't, however, find a place to download it from, nor can I search for it on my Wordpress dashboard under Appearance -> Themes.
The best I could find was this svn url: <
Does anyone know how I can get the theme?
< | To get a theme or plugin for which you have just the SVN URL you need three steps:
1. Install a SVN client. For Windows you might take TortoiseSVN.
2. Create an empty directory where you need the code.
3. Right click in that directory and use the **Checkout** command to download the code.
!enter image description here
After you have clicked **OK** all the files are fetched from the remote repository.
> !enter image description here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes"
} |
Change wordpress Multisite default site from side id 1 to side id 2
I have a multsite installation with canonical setup like `site1.domain.com` and `site2.domain.com` etc. How do I change the default root site from site `1` to site `2`?
I tried to change these two values in `wp-config` to `5` instead of `1` and there was no effect:
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );
Is there a tutorial out to do this? | Current site Id defines the primary network id. You can have more than one network if you use a multi-network plugin. Current blog id defines the primary blog within the primary network. To change the main blog to '2' (if you only have one network) you want your defines like this:
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 2 ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "multisite"
} |
Use register_post_type() to modify an existing post type
There are lots of situations where a theme or plugin registers a post type and you want to modify it. There is of course `add_post_type_support()` and `remove_post_type_support()`, but those don't give access to the full list of arguments that `register_post_type()` takes. In particular, maybe I want to disable a post type archive, hide the admin UI, hide from search, etc. while leaving the rest of the post type settings alone.
The Codex page for `register_post_type()` dangles this in front of me:
> ## Description
>
> Create or modify a post type.
But in the past, when I've try to do this, it hasn't seemed to work. Is this function really for modifying post types, and if so, can you simply redeclare a couple arguments and leave the rest alone?
Seeing that there isn't even a `deregister_post_type()` function, I don't understand how it can be done. | > Is this function really for modifying post types
Yes.
> and if so, can you simply redeclare a couple arguments and leave the rest alone?
No. If you want to modify arguments to a post type, you need to use `get_post_type_object` to get the post type object, modify what you want in it, then re-register it using your modified type as the new $args parameter. | stackexchange-wordpress | {
"answer_score": 20,
"question_score": 37,
"tags": "custom post types, post type"
} |
Overwrite default WordPress wording
I'm working on a plugin that changes the password requirements to be a bit stricter, however wherever there is a password field to create a password, WordPress' hints are now no longer accurate (e.g. Password must consists of seven characters).
How can I replace those hints? Is there a filter/function that can help with this? | You can filter `'gettext'`.
Sample code, not tested:
add_filter( 'gettext', 'wpse_65085_change_error_messages', 10, 3 );
function wpse_65085_change_error_messages( $translated, $text, domain )
{
if ( 'default' !== $domain )
{
return $translated;
}
switch( $text )
{
case 'Hint: The password should be at least seven characters long. To make it stronger, use upper and lower case letters, numbers and symbols like ! " ? $ % ^ & ).':
return __( 'Use whatever you want', 'your_plugin_text_domain' );
// more cases here.
default:
return $translated;
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "filters, language"
} |
How can i add thumbnails images to particular post (using code not admin pannel) in wordpress
I am trying to set thumbnails for my post.
I have `post_id = 285` and I want to add manually a thumbnail (using code) but I'm not succeeding.
update_post_meta( $post->ID, '_thumbnail_id', $attachment_id );
I got this function reference but I do not understand what is the `$attachment_id` and how can I get it.
I have also image name and path of image. | First you'll need to upload the image, like this. This will upload the image and add a row to `wp_posts` where your attachment is.
How dynamic do you need this to be? Can you upload the image with the user interface or does that have to be done programatically as well?
In your case, the third parameter of `update_post_meta()` should be the ID of the image in the wp_posts table.
**Edit:** This is more what you need regarding the image upload: How to add image to post programmatically?. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, posts, images, post thumbnails"
} |
Where do I add html code to the menu div?
When looking at header.php, I see the following line:
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
That function is defined in nav-menu-template.php and generates the 'menu-custom-menu-container' div. Let's I want to add a div after the navigation list inside the 'menu-custom-menu-contaner' div. Where would I do that? | wp_nav_menu( array( 'theme_location' => 'primary'
,'items_wrap' => '<ul id="%1$s">%3$s</ul><div><p>content</p></div>' ) );
See @toscho's detailed explanation of the items_wrap parameter for more information. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, menus"
} |
How to Reload the Dashboard After Clicking Update in Quick-Edit?
How can I refresh the `wp-admin/edit.php` page after a user clicks **Update** in the _Quick-edit_ form? | I dug through WordPress' `wp-admin/js/inline-edit-post-dev.js` and found that there aren't any hooks for executing JS code after the quick-edit update.
I decided to override the `inlineEditPost.save` function from `wp-admin/js/inline-edit-post-dev.js`, similar to how WordPress recommends updating form data when the quick edit form is displayed (which overrides `inlineEditPost.edit`).
The full function can be found in `wp-admin/js/inline-edit-post-dev.js`. I just changed the callback function in the post call to reload the page instead of hiding the quick edit form.
(function($) {
inlineEditPost.save = function(id) {
//...
// make ajax request
$.post( ajaxurl, params,
function(r) {
location.reload();
}
, 'html');
//...
}
})(jQuery); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, javascript, quick edit"
} |
Add column to plugins table screen
I'm trying to add a column to plugin table screen using "manage_plugins_custom_column", but without success.
This extra column will show a custom value that was placed inside the plugin file.
I hope someone could help!
Thanks! Daniel
\---------------- edit ----------------
This is the working code that creates the column "Version":
function add_plugins_column( $columns ) {
$columns = array(
"name" => __( 'Plugin', '' ),
"version" => __( 'Version', '' ),
"description" => __( 'Description', '' ),
);
return $columns;
} add_filter( 'manage_plugins_columns', 'add_plugins_column' );
function render_plugins_column( $column, $plugin_file, $plugin_data ) {
switch ($column) {
case "version": echo $plugin_data['Version']; break;
}
} add_action( 'manage_plugins_custom_column' , 'render_plugins_column', 10, 3 ); | First, you have to add the custom column to the plugin column names:
function wpa65189_add_plugins_column( $columns ) {
$columns['wpa65189_column'] = 'wpa65189 Custom Column';
return $columns;
}
add_filter( 'manage_plugins_columns', 'wpa65189_add_plugins_column' );
Then output your column data for your plugin:
function wpa65189_render_plugins_column( $column_name, $plugin_file, $plugin_data ) {
if ( 'wpa65189_column' == $column_name && 'My Plugin Name' == $plugin_data['Name'] ) :
echo 'My Plugin custom column data';
endif;
}
add_action( 'manage_plugins_custom_column' , 'wpa65189_render_plugins_column', 10, 3 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, screen columns"
} |
Hide Menu items base on capability
What is the best way to add/remove items for the `wp_nav_menu()` based on user roles?
For instance a custom menu that looks like:
* Some Page
* Some Other Page
* Special Admin Page
Where the `Special Admin Page` should only be visible for admin users.
Is this best done with `wp_nav_menu_items` filter or do I need a custom Walker?
This is a possible duplicate of: Hide menu items for visitors and filter based on role but that doesn't appear to have been completely solved. Though it does mention a tutorial about a custom Walker that seems relevant.
**EDIT:**
Based on Toscho's answer and How to add a custom field in the advanced menu properties? I combined the two to form my own plugin
Nav Menu Roles
Fair warning that I cannot vouch for its speed and I am relatively certain that it will not work _with_ another custom Walker, but it was a one-day plugin. | Create a custom walker. Redefine the method `start_el()` only:
function start_el( &$output, $item, $depth, $args )
{
if ( 'Your secret item title' !== $item->title
or current_user_can( 'administrator' )
)
{
parent::start_el( &$output, $item, $depth, $args );
}
}
Please mind that this is just pseudo code. I can not give it a test at the moment. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "menus, user roles"
} |
fetch meta fields inside a widget
I'm trying to fetch a (date) meta field from a custom post type in a sidebar widget here: <
Somehow the date doesn't show correctly inside the widget (everywhere else I put it, also manually in the sidebar the code works fine). Anyone a clue?
The code looks like this:
<?php $loop = new WP_Query(array(
'post_type' => 'kurs',
'posts_per_page' => '5',
'meta_key' => 'dato',
'meta_value' => date('Y-m-d'),
'meta_compare' => '>=',
'orderby' => 'meta_value',
'order' => 'ASC'
)); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $display_date = date('d.m.Y', strtotime(get_post_meta($post->ID, "dato", true))); ?>
<li><?php echo $display_date; ?> - <?php the_title( '<a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a>' ); ?></li>
<?php endwhile; ?>
</ul> | I fixed this by adding:
global $post;
More specific: I can't explain why this works, that's beyond my WordPress skills, but I added it right after the start of the query, so the code looks like this:
<?php global $post;
$loop = new WP_Query( array(
'post_type' => 'kurs',
'posts_per_page' => '5',
'meta_key' => 'dato',
'meta_value' => date('Y-m-d'),
'meta_compare' => '>=',
'orderby' => 'meta_value',
'order' => 'ASC'
) ); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, widgets, post meta"
} |
Plugin - create a page without it appearing in the side menu
I am currently using add_submenu_page to add pages for my plugin. However, I wish to create a page that don't appear in the admin menu, is that possible? | Set the **`parent_slug`** property to **`null`** , example;
add_submenu_page(
null // -> Set to null - will hide menu link
, 'Page Title' // -> Page Title
, 'Menu Title' // -> Title that would otherwise appear in the menu
, 'administrator' // -> Capability level
, 'menu_handle' // -> Still accessible via admin.php?page=menu_handle
, 'page_callback' // -> To render the page
);
This will hide the sub menu page from your parent (top level) menu link.
~~It does not state this in the **Codex** entry for **`add_submenu_page`** though.~~
It now states this in the **Codex** entry for **`add_submenu_page`** (thanks goto Ian Dunn). | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 9,
"tags": "plugin development, add submenu page"
} |
Custom action on comment post
Whenever a user posts a comment, I'd like to basically have a copy of the post sent to another database for a separate site. The database part is simple, but I can't seem to find the right action hook for this. (I did my testing with a simple echo statement, a failure being it not displaying at all) 'comment_save_pre' would only work when updating a comment, 'wp_set_comment_status' only works when the comment is approved, and 'comment_post' didn't seem to work at all. Does the hook exist?
add_action('...?...', 'on_comment_post');
function on_comment_post($comment){
echo "Test";
} | You can use `wp_insert_comment` action, which is triggered on every comment insertion. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, comments, actions"
} |
How to disable the default WordPress redirect to non-www URLs?
I am trying to redirect all non-www to www URLs in my WordPress MultiSite install. I am using a simple `.htaccess` rule like this:
# Redirect non-www to www:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ [R=301,L]
Normally this would work, however WordPress already seems to have a default redirection to non-www URLs. This means that when I use that `RewriteRule` it causes an infinite redirect loop.
**How do I disable this?**
PS. I tried `define('NOBLOGREDIRECT', ' in `wp-config.php` with no effect. | Answer: Don't disable it, use it to do the redirection you want.
* If you have a subdomain install, then you cannot do this at all, the www is a subdomain.
* If you have a sub-directory install and want all the sites to be www, then edit your wp-config.php and change the DOMAIN_CURRENT_SITE to be your www domain.
* If you are using domain mapping, then use the domain mapping plugin to change the domain to have a www in it.
In the latter two cases, the point is that you're not using .htaccess to do the redirection, you're letting WordPress do the redirection to what it expects the URL is supposed to be. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "multisite, url rewriting, redirect, htaccess, wp config"
} |
Comment number does not increment
I am making a custom wordpress theme and when I add a comment to a post and retrieve the number of comments using `get_comments_number()` the number does not change.
I do know the function works because for the first comment that gets preinstalled with wordpress it returns 1. but somehow the number does not increment if I add additional comments.
Is there a way to manually increment this number? Does anyone know what the problem might be?
Thanks for your suggestions! | Approving them in the admin console solved my problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "comments"
} |
Pretty URLs with Categories and Tags
How do I create pretty permalinks for a query page that includes results from both categories and tags.
For instance, if the category is Country (America) and the tag name is city (New York), can I have a permalink like wordpressblog.com/america/new-york for a page that shows all posts belonging to Amercia category and NY tag?
Thanks much! | You could do it manually in your .htaccess although I'm not sure how. In the past I have been able to use partially pretty urls by doing
`
I would imagine it would easy enough to use mod_rewrite to prettify that even further.
UPDATE: Check this out it looks like it will do exactly what you need!
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, tags"
} |
How to call bind function in wordpress actions or hooks
I have made a class file in my plugin folder. Then I wrote,
class Sample{
function footer_content(){
echo "show any data";
}
}
Then I added the function **footer_content** to wordpress footer by using **add_action** command. But it didn't show anything. maybe I am missing something in this, as it is not working.
add_action('wp_footer', Sample::footer_content()); | Here's reference from Codex
> To use the add_action hook when your plugin or theme is built up using classes, add $this to your add_action call together with the function name within that class, like so:
class MyPluginClass {
public function __construct() {
//add your actions to the constructor!
add_action( 'save_post', array( $this, 'save_posts' ) );
}
public function save_posts() {
//do stuff here...
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins, plugin development, actions"
} |
Force redirect single.php to index
I want to make a force redirect for single.php to index so that it is never reachable by direct access (the site is built in a way that you retrieve all the content on the index page, still need to have this page available though because of an ajax function). I assume this is done in .htaccess?
Edit: I need to be able to access the single.php through an ajax request from the index page, i.e. the redirect should only occur upon direct url access. | put this code in functions.php file
add_action('wp', 'myfun');
function myfun(){
if(is_single()){
wp_redirect( home_url() ); exit;
}
}
hope this trick solve your problem. all the best ;) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "ajax, redirect, htaccess, single"
} |
Inserting images in multiple posts native gallery
I am trying to find a solution to a problem that Wordpress seems to lack.
Here is a scenario:
I have uploaded images to a post using the native gallery to display the images. These images then appear under the gallery tab within the upload/insert and they will appear on the post. Works perfectly.
Further down the line I create a new post, I want to include images from my Media Library into the gallery without re-uploading the same images again.
I expected to find, "Insert into gallery", next to "Insert into post", but there doesn't seem to be a way of doing this.
Is there a solution to this? I have done a lot of theme development in the past, but amazed at there isn't a simple solution to this problem.
I would be grateful for any help. | Attachments are a type of post, and a post can only have a single parent, that's why it's not natively possible to have an attachment associated with multiple posts- there is no mechanism for many-to-many associations. There are several ways to solve this, but how simple it is depends on your skill level or willingness to depend on plugins.
For plugins, there's File Gallery, and Advanced Custom Fields, probably others. Otherwise a couple of custom solutions would be to use post meta data to store references to attachments for a post, and/or a taxonomy to "tag" images for each unique gallery you want them associated with along with some meta data for ordering them.
Here is a thread on WordPress Hackers with an explanation from the lead developer and some possible solutions. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, images, dashboard"
} |
Is it possible to set individual shipping prices in Woocommerce?
I currently have a store running on Bigcommerce, but unfortunately it doesn't offer the functionality that I require. I am debating whether to use a magento/wordpress install or wordpress/woocommerce.
Does anybody out there know if it is possible with woocommerce (or additional plugins) to perform the following:
Set an individual item with a fixed shipping price to different regions/countries.
Offer a free shipping option on orders of a particular item over a given amount.
I believe this would possible with magento, but it appears to be a quite heavy weight option for a wordpress blog/ e-commerce store.
Thanks in advance for any assistance with the above. | Just to help you out ... Wordpress and Magento are comparable as they are both PHP content management systems. However Magento doesn't compare to WooCommerce in the way you mention it above.
For example: you may not need WordPress if you installed Magento. But you have to install WordPress to use WooCommerce.
What you are looking for is Table Rate Shipping this is part of the Magento functions, but you'd need to buy the Table Rate premium extension from WooCommerce to achieve this. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "e commerce, plugins, magento"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.