INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to activate "Description" metabox for menu item programmatically?
I'm creating custom wordpress theme. How can I enable "Description" metabox for menu items (on nav-menu page) by default programmatically? | Remove the `description` from the user meta value `managenav-menuscolumnshidden`:
add_filter( 'manage_nav-menus_columns', 'enable_nav_menu_description_by_default' );
function enable_nav_menu_description_by_default( $columns )
{
$desc_key = 'managenav-menuscolumnshidden';
$hidden = get_user_option( $desc_key );
$user_id = wp_get_current_user()->ID;
if ( ! $hidden )
{
update_user_option(
$user_id,
$desc_key,
array ( 0 => 'link-target', 1 => 'css-classes', 2 => 'xfn' )
);
}
elseif ( FALSE !== ( $key = array_search( 'description', $hidden ) ) )
{
unset( $hidden[ $key ] );
update_user_option( $user_id, $desc_key, $hidden );
}
return $columns;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "functions, menus, metabox"
} |
Display just child pages of a certain page in search results
StackExchangers!
I have searched the internet left right and center and still cannot find a way to alter the search results that are displayed. Basically I would like no posts and only child pages of this parent page to be displayed in the search results of my WP Site:
<
Otherwise, if none of these pages are displayed it would display null results.
Any help/direction is appreciated, I did try and gather as much information from here, forums and asking webdev friends - But I am completely stuck so I have resorted to asking StackExchange.
Hopefully this isn't too broad and you understand what I have been trying to figure out for days, otherwise if not, please ask for what you need and I can provide. | Try the following approach.
Get the page using `get_page_by_path()`
<
$page = get_page_by_path( 'university-guide' );
$search_query['post_type'] = 'page';
$search_query['post_parent'] = $page->ID;
The following snippet was taken from Codex page: Creating a search form <
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach
$search = new WP_Query($search_query);
Search results are obtained using WP_Query instance.
You can use WP_Query codex page to learn more about available options. < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "search"
} |
Homepage custom recent news
Is there anyway of telling wordpress, by some plugin or whatever, not to show Recent news from Category X, on my home page?
Or I may do it only by modifying the `home.php` code? | Assuming this is the default main query, see the example for `pre_get_posts`, which shows how to exclude a category from the main query:
function wpa78465_exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-1,-1347' ); // IDs of categories to exclude
}
}
add_action( 'pre_get_posts', 'wpa78465_exclude_category' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, homepage, exclude, recent posts"
} |
How and when to include shortcode source files
I am Writing a plugin, with many shortcodes. Now I do not want to include all shortcodes source files to every page. So my questions are:
1. Where should I include the source? Is it back-end or front-end
2. How to add it on that specific page?
thanks HoGo | The pattern I use is:
* break code into modules using classes
* use spl_autoload_register() to load classes (thereby only included when used)
* have a class that is the plugin controller, with a method for each shortcode
* those methods generally do nothing but create instance of shortcode class and pass params
Works for me, simplifies things greatly, especially for large sites where I have dozens of classes. No need to carefully manage what gets included where because the class autoloader handles that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode, include"
} |
get_comments() where parent is not 0
I need a way to get just the comments that aren't top level i.e. where parent is not 0.
I've tried:
$args = array(
'parent' => -0
);
$comments = get_comments($args);
I know the parent comment id's (44 and 48) of all the comments I require, so I tried:
$args = array(
'parent' => array(44,48)
);
$comments = get_comments($args);
But this didn't work. It only returned one row. I need to stick with get_comments() if possible, as I've done a lot of work around it already so want to avoid losing what I've done. | You cannot do that with a parameter for `get_comments()`, but filtering `'comments_clauses'` should do it.
Sample code, not tested:
add_filter( 'comments_clauses', 'wpse_78490_child_comments_only' );
function wpse_78490_child_comments_only( $clauses )
{
$clauses['where'] .= ' AND comment_parent != 0';
return $clauses;
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "comments"
} |
Translating long texts with html formatting
I was wondering what is the best way to translate some longer texts with html formatting. There was a couple of solutions I came across, but did not know what would be the best one.
* Writing a couple of html files with language extension (e.g. maintext_en.html, maintext_de.html, ...) and import this files.
_Pro_ : It's easy for me
_Contra_ : Not so easy for translators
* Writing only one html file with some markers and parse the file.
_Pro_ : A bit easier for translators, they have to edit only one file.
_Contra_ : I need a parser
* Using l10n inside the code
_Pro_ : The easiest way for translators
_Contra_ : Uses a lot of memory when the plugin runs. And the risk of losing some formattings.
What is the best and most efficient way to make long texts within a plugin translateable? | Most translation tools are really hard to use when you try to handle a long text, so the translators have to use a HTML editor anyway. Use separate files, but use the language prefix as directory name:
* en
* main.html
* help-main-options.html
* help-special-options.html
* de
* main.html
* help-main-options.html
* help-special-options.html
That’s easier to handle for translators and for you too.
You could also set up a WordPress site for translations and use a custom post type, so translators can use the regular editor (outdated example), and you handle just the import and export. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, customization, translation"
} |
Frontend tag edit/submit form
I would like to have a separate page to submit/edit tags.
Any user can edit or submit tags. But it should be published only after admin approval.
Is there any function available like `wp_insert_tag()`?
## Update:
After Kaiser's answer I've tried like this.
$x = wp_insert_term( 'test', 'post_tag', array('description' => 'This is a test tag') );
var_dump($x);
Its working fine. But it gets published automatically. Is it possible to publish it after admin approval? | In case that
1. I have understood your (very brief) question and
2. you're not actually talking about the `post_tag`-taxonomy
then you have `wp_insert_term()`, which is the underlying API function.
### Edit
As to the comment, there's the need of meta data for a term and administrator approval.
WordPress currently has **no** native way of adding meta data to a taxonomy taxon. There're ideas "around" it. _IMHO_ they clutter your DB-options table in seconds without a reason. There're other ways around this, but this would be too much for a single answer, so I can only recommend to find another way of handling tag maintenance. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, tags, wp insert post"
} |
Restore Image Title Text
In WordPress 3.5, when images are inserted into posts, the title attribute is not included in the image tag.
The Lightbox plugin I am using requires the title tag to be present on images; besides, I like having a hover tool-tip.
Is there some way to restore the previous behaviour of including the title attribute? | You can hook into the `media_send_to_editor` filter and add the title tag to the generated HTML image tag:
function wpse_78529_restore_image_title( $html, $id ) {
/* retrieve the post object */
$attachment = get_post( $id );
/* if the title attribute is already present, bail early */
if ( strpos( $html, 'title=' ) )
return $html;
/* retrieve the attached image attrbute */
$image_title = esc_attr( $attachment->post_title );
/* apply the title attribute to the image tag */
return str_replace( '<img', '<img title="' . $image_title . '" ', $html );
}
add_filter( 'media_send_to_editor', 'wpse_78529_restore_image_title', 15, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, media"
} |
Thumbnail is corrupt but image is good
I am using wordpress 3.5 to manage my website with a template (not sure which). Lately, each picture I add to a gallery creates a corrupted thumbnail, but the picture itself shows up ok. I tried uploading pictures that used to create a proper thumbnail and now their new thumbnail is broken.
The broken thumbnail link \- though it opens up correctly...
!broken thumbnail
How can set to fix this? | You may need to reset the thumbnail settings in your media settings, then regenerate the thumbnail; either:
* use Regenerate Thumbnails plugin to rebuild all thumbnails; or
* edit image / rotate it left / rotate it right (back to original) / save image | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "thumbnails"
} |
Which file displays the date archive?
I'm building a new theme. I'm now working on to figure out which file is needed to show the "whole" post for a specific date which displays when you click on a date in the built in WordPress calendar widget?
Somebody who has a clue which it is? | `archive.php` is used to display author, search, category, tag and **date** archives. As clicking on a calendar day will take you to the date archive for that day, then the file you're looking for is `archive.php`.
More specifically, WordPress will check for these files in this order, stopping when it finds one of these files in your active theme's folder:
1. `date.php`
2. `archive.php`
3. `index.php`
Read more at the WordPress Codex | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, widgets, calendar"
} |
Capture Webcam Video within Buddypress (and BuddyPress Media)
Has anyone had experience capturing video from a webcam and adding it to a users album inside of BuddyPress and BuddyPress Media? BuddyPress Media isn't necessary if there's a better solution
BP Media has a premium FFMPEG add-on for converting video which I think will be needed if this is possible; but I have no real experience with hosting, recording, and converting video on a custom site i.e. not within Vimeo or YouTube | I'm from the team that developes BuddyPress Media.
Till now, capturing a video involved expensive (in various ways) setups. It depended on flash and silverlight which could reach the hardware (mic and webcam) . Html5 is the way to go, now. However, the support isn't wide enough. This might help you: <
If you do wish to develop such a solution, do get in touch with us at rtCamp < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "buddypress, videos"
} |
Fix html inside a for loop
I want to get the right link format for the second link, i tried many time to move the a open tag but no way the result is as the image below.
foreach( $terms as $term ) :
echo '<div class="one_half last">';
$customposts = new WP_Query( "taxonomy=$taxonomy&term=$term->slug&posts_per_page=2" );
echo '<ul>';
if( $customposts->have_posts() ): while( $customposts->have_posts() ) : $customposts->the_post();
echo '<li>';
echo '<a href="'.the_permalink().'">'.the_title_attribute(); // The problem
endwhile; endif;
echo '</a></li>';
echo '</ul>';
echo '</div>';
endforeach;
Thanks!enter image description here | First of all you have the PHP syntax all messed up. Second, you misused some WordPress template tags - you already echo the entire link like so you need to return post permalink and title, but right now `the_permalink` and `the_title_attribute` functions echo the code.
Here's your code fixed:
foreach( $terms as $term ) :
$customposts = new WP_Query( "taxonomy=$taxonomy&term=$term->slug&posts_per_page=2" );
if( $customposts->have_posts() ):
echo '<div class="one_half last">';
echo '<ul>';
while( $customposts->have_posts() ) : $customposts->the_post();
echo '<li>';
echo '<a href="' . get_permalink() . '">' . get_the_title(); // The problem
echo '</a></li>';
endwhile;
echo '</ul>';
echo '</div>';
endif;
endforeach; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "loop"
} |
How to delete ALL comments from certain category in Wordpress database?
I'm trying to delete all comments from posts in a certain category in a Wordpress database.
The Wordpress database is rather complicated so this must be probably some join of `wp_posts`, `wp_comments` and `wp_term_relationships` as the categories are not stored with neither posts nor comments.
How can I do this? I'm struggling to come up with a query. | The wordpress database seems fairly straight forward and is extremely well documented:
<
It seems to me that all the category information is stored in the table **wp_term_relationships**. So you should select from the comments table, join it with the posts table and then the term_relationships table in order to get the category for each comment.
Something like:
SELECT *
FROM wp_comments
WHERE comment_post_ID
IN (
SELECT c.object_id
FROM wp_terms a, wp_term_taxonomy b, wp_term_relationships c
WHERE a.name = 'my_category_slug'
AND b.term_id = a.term_id
AND b.taxonomy = 'category'
AND c.term_taxonomy_id = b.term_taxonomy_id
) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sql, comments"
} |
Wordpress DB: options-table –> 32 gzipcompression?
I just wondered what this row in the Wordpress Database refers to?
32 gzipcompression 0
I stumbled upon it in the WP options table. What if I set the value to `1`.
I do already have gzipcompression enabled via htaccess, so I simply wondered what this is?
Thank you for your answer. | It's set in `schema.php`, the WordPress Administration Scheme API. You can also find it in the Codex.
As you can see from a search through core, there's (as far as my search went) **exactly no use case** for it, aside from defining it as `0` when adding that option to the DB.
If you want to know if it's working on your site, just enter your URL here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "database, options, compression"
} |
Which version of PHP-FPM is necessary to work with WP 3.5?
I'm trying to establish a blog with NGINX and PHP-FPM.
I wonder if my version of PHP should work with WordPress
/usr/bin/php-cgi -v
PHP Warning: PHP Startup: magickwand: Unable to initialize module
PHP 5.2.17 (cgi-fcgi) (built: Sep 17 2012 00:15:25)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2010 Zend Technologies
with eAccelerator v0.9.6.1, Copyright (c) 2004-2010 eAccelerator, by eAccelerator` | According to the official system requirements, PHP version 5.2.4 or greater should work. However, some plugins and / or themes may require PHP version 5.3, though. BTW, PHP 5.2 has reached its End of Life a couple of year back (in 2011). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, nginx"
} |
Can the wp-plugins (Must Use Plugins) URL be targeted for use in functions.php?
Can the wp-plugins (Must Use Plugins) URL be targeted for use in functions.php? I have a mu-functions.php file in the mu-plugins folder. One function calls a javascript file (`alerts.js`) located in `example.com/wp-content/mu-plugins/js/`. How can I target the mu-plugins folder in my function?
Currently, I am using `get_site_url() . '/wp-content/mu-plugins/js/alerts.js',`
Although not completely relevant to the question, this is the complete function used to call the javascript file:
function load_my_alerts(){
wp_register_script(
'my_alerts',
get_site_url() . '/wp-content/mu-plugins/js/alerts.js',
array( 'jquery' )
);
wp_enqueue_script( 'my_alerts' );
}
add_action('admin_enqueue_scripts', 'load_my_alerts'); | **EDIT: this solution is not a best-practice. Please use the solution submitted by Nathan below!**
Use the `WPMU_PLUGIN_DIR` and `WPMU_PLUGIN_URL` constants :)
function load_my_alerts(){
wp_register_script(
'my_alerts',
WPMU_PLUGIN_URL . '/js/alerts.js',
array( 'jquery' )
);
wp_enqueue_script( 'my_alerts' );
}
add_action('admin_enqueue_scripts', 'load_my_alerts'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "functions, mu plugins"
} |
Passing variables trough 2 pages
I am creating a plugin. In this plugin I have shortcodes that provide some logic and content for pages. This way I have created 'Page A' and 'Page B'. Both of the pages will redirect user to external page. The external page is not written by me and will not process any of my $_GET or $_POST values. Then this external page will redirect user back to my plugin 'Page C'. Now how to make 'Page C' know if the external page was reached from 'Page A' or 'Page B'? Normally I would use sessions, but I have read that wordpress does not support sessions. How can I do it then?
HoGo | I really have no idea what you're implementing here - I don't know how a plugin "has pages," for instance. As such, I'm afraid I cannot offer you much help in the way of an example, but I'm confident that what you ask could be accomplished using the Transients API, or its ascendant the Options API (preferably Transients as Options exist indefinitely and you seem to only require the data temporarily, for the duration of a couple page requests). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "variables"
} |
Using meta query ('meta_query') with a search query ('s')
Trying to build a search that not only searches the defaults (title, content etc) but also a specific custom field.
My current query:
$args = array(
'post_type' => 'post',
's' => $query,
'meta_query' => array(
array(
'key' => 'speel',
'value' => $query,
'compare' => 'LIKE'
)
)
);
$search = new WP_Query( $args )
...
This returns posts which match both the search query AND the meta query, but I would also like it to also return posts where it simply matches either one of them.
Any ideas? | As per Nick Perkins' suggestion, I had to merge two queries like so:
$q1 = get_posts(array(
'fields' => 'ids',
'post_type' => 'post',
's' => $query
));
$q2 = get_posts(array(
'fields' => 'ids',
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'speel',
'value' => $query,
'compare' => 'LIKE'
)
)
));
$unique = array_unique( array_merge( $q1, $q2 ) );
$posts = get_posts(array(
'post_type' => 'posts',
'post__in' => $unique,
'post_status' => 'publish',
'posts_per_page' => -1
));
if( $posts ) : foreach( $posts as $post ) :
setup_postdata($post);
// now use standard loop functions like the_title() etc.
enforeach; endif; | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 37,
"tags": "custom field, search, meta query"
} |
wpdb->prepare function remove single quote for %s in SQL statment
I am using the below wpdb->prepare function in a sql statement. I am passing in several variables some field names and some values. When I try to use the %s for the field name it puts single quotes around it. How can I prevent the single quotes around the field name? The sql statement will not execute with the single quotes?
` $query = $wpdb->prepare("SELECT DISTINCT wp_geo.%s, wp_geo.$field2 FROM wp_geo WHERE wp_geo.$field3=%s",$field1, $typevalue);`
Output with single quotes around 'county_short' field name:
`SELECT DISTINCT wp_geo.'county_short', wp_geo.county_slug FROM wp_geo WHERE wp_geo.type='trailers'` | You cannot suppress the quotes in $wpdb. Run `mysqli_real_escape_string()` in _your_ script on these variables. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "mysql, sql, wpdb"
} |
adding GET variables to a header() location in a page template
header('Location: /page-name/?var1='
. $_GET['var1'] . '&var2=' . $_GET['var2'] );
exit();
The result of the above code ends up redirecting the site to:
I have a feeling Wordpress is cleaning the ampersand in the URL, but I don't at what point it would do that...
Edit: With Milo's direction, I modified the redirect code to look like this and it started working properly.
$url = '/page-name/';
$args = array('var1'=>$_GET['var1'], 'var2' => $_GET['var2']);
$url = add_query_arg($args, $url);
wp_redirect($url);
exit();
I'd still like to know why the ampersand got converted to HTML in the first place. | WordPress has API functions for doing both of these things- `wp_redirect` and `add_query_arg`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "redirect, page template"
} |
xmlrpc_enabled filter not called
Since WordPress 3.5, the core developers have decided to keep xml rpc enabled by default and there are no options in the Admin to disable it.
This blog post explains how to disable it by modifying the xmlrpc_enabled filter
add_filter('xmlrpc_enabled', '__return_false');
But this doesn't seem to work, I still get the following on the generated HTML
<link rel="EditURI" type="application/rsd+xml" title="RSD" href=" />
and WordPress still generates the ` page
I'm putting the filter in the `functions.php` file of my theme. | To remove the HTML link:
remove_action( 'wp_head', 'rsd_link' );
To stop all requests to `xmlrpc.php` for RSD per XML-RPC:
if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) )
exit;
This is plugin territory. Never use this code in a theme. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "filters, xml rpc"
} |
How do I make Contact Form 7 pop up in thickbox?
I am trying to make contact form 7 pop up in a thickbox modal window. I can either use `do_shortcode` or the shortcode but I'm not sure how to set it up. Can someone push me in the right direction?
From the Thickbox page, it looks like I should be using either inline Content, iFramed Content, or AJAX Content, but I'm not sure which one. | A solution I can think of is creating an almost empty page template that contains the bare minimum `header`, `body` (your shortcode) and `footer`.
Create a page with this template and load iFramed.
Like:
<?php
/**
* Template Name: Almost Empty Page for Thickbox
*/
// REPLACE THIS get_header WITH THE CONTENTS OF THE FILE header.php
// AND CLEAN UP EVERYTHING THAT'S NOT NEEDED
get_header();
?>
<div id="container" class="one-column">
<div id="content" role="main">
<?php
do_shortcode(); // YOUR SHORTCODE
?>
</div>
</div>
<?php
// REPLACE THIS get_footer WITH THE CONTENTS OF THE FILE footer.php AND CLEAN UP
get_footer(); ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, plugin contact form 7, thickbox"
} |
Knowing the total number of posts before to get into the loop
Is there a way to know the total number of posts before the loop starts? I'm thinking in use two loops. The first will do the counting, while the second one will handle the content. However, I don't think this approach is 'elegant'. Any other solutions? | functions.php:
function wpse8170_get_posts_count() {
global $wp_query;
return $wp_query->post_count;
}
index.php:
if (have_posts()) :
echo '<h1>' . wpse8170_get_posts_count() . ' Posts Found</h1>';
while ( have_posts() ) :
the_post();
//...
endwhile;
endif; | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 5,
"tags": "php, loop"
} |
Implementing an OR statement to wordpress wp_query
I am trying to return all posts that meet the following conditions:
The category must be 63
OR
the post must have a value associated with the meta key named 'android_link'
My current argument array currently does not work because it is asking for both of these conditions to be met. Is it possible to change it so that only one of these conditions must be met to return a post?
$args = array(
'paged' => $paged,
'order' => 'DESC',
'meta_key' => 'android_link',
'post_type' => array( 'post', 'app' ),
'cat' => '63',
'meta_query' => array(
array(
'key' => 'android_link',
'compare' => 'EXISTS',
)
)
); | You can run two queries and merge") the results:
$cat_query_args = array(
'paged' => $paged,
'order' => 'DESC',
'meta_key' => 'android_link',
'post_type' => array( 'post', 'app' ),
'cat' => '63',
);
$meta_query_args = array(
'meta_query' => array(
array(
'key' => 'android_link',
'compare' => 'EXISTS',
)
)
);
$cat_query = new WP_Query( $cat_query_args );
$meta_query = new WP_Query( $meta_query_args );
$merged_query_args = array_merge( $cat_query, $meta_query );
$merged_query = new WP_Query( $merged_query_args ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "wp query, loop"
} |
Hide the 'Gallery Settings' section of the Gallery tab of the media Thickbox
When I invoke the media uploader from a certain page, I'm looking for a way to hide all of the 'Gallery Settings' options at the bottom of the Gallery tab. I have set a referrer (`dd-options-footer`), so I can check that to ensure the code is only added for my desired page, but it seems that whatever I add does not work.
I've tried adding both custom CSS and JS to do this, but it appears that WP overrides this in `wp-admin/js/gallery-min.js` when it outputs the content of the tab.
Anyone know how I can do this? Thanks. | David, I'm not sure if you're trying to disable the whole gallery (plus the settings) or only its fields. For the first option, you should try do deregister the `admin-gallery` script:
function disable_gallery() {
$post_id = (int) $_GET['post_id'];
// Check for your post / page ID
if( $post_id == 343 ) {
wp_deregister_script( 'admin-gallery' );
}
}
add_action( 'admin_enqueue_scripts', 'disable_gallery' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "gallery, thickbox"
} |
Wordpress Navigation default output
Could someone please give me the Wordpress default navigation output, i've searched it around but havn't found it.
I would like the example navigation to also include one sub-menu link.
Or if someone could point me out to a link where i could find information about this and customizing, thanks. | wp_nav_menu is what you are looking for.
Here are some examples.
Using the depth parameter you can change the level of sub-menu.
0 leads to all levels.
Ex.
<?php
$defaults = array(
'theme_location' => '',
'menu' => '',
'container' => 'div',
'container_class' => '',
'container_id' => '',
'menu_class' => 'menu',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
wp_nav_menu( $defaults );
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, navigation"
} |
Getting term_id for newly created or edited term
I'm taking my first foray into plugin development and have got confused pretty quickly. I'm attempting to make a simple plugin that stores hex colours against terms, so you can assign a colour to a tag or category and then use that in a theme.
What I cant figure out is how to get the term_id of a newly created or edited term. I've bolted on a form to 'edit_tag_form' with a colour picker and can access these values through $_POST, but if it's a newly created tag I don't see how my code can know the ID of the newly created one. I need to know the term_id to be able to link it with the hex colour and save it to wp_options.
I'm using the action hook 'edited_term'. I guess for edited existing terms I could get the tag_ID from the query string, but I want to be able to assign colours immediately to newly created tags/categories. | Use the action `created_term`. Its first parameter is the `$term_id`.
It is called in `wp_insert_term()` in `wp-includes/taxonomy.php` after a term was successful created:
do_action("created_term", $term_id, $tt_id, $taxonomy);
do_action("created_$taxonomy", $term_id, $tt_id);
The second parameter is the term_taxonomy_id from the `term_taxonomy` table, and the last parameter is the taxonomy.
So register an action with …
add_action( 'created_term', 'wpse_78858_add_color', 10, 3 );
… and your callback should look like this:
function wpse_78858_add_color( $term_id, $tt_id, $taxonomy )
{
# do something
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development"
} |
insert order number into wp ecommerce order confirmation email
A client site has been barred from using Paypal, so their WP-e-Commerce catalog/cart now has to use manual EFT bank payments to accept money from customers. A customer receives this banking information in their order confirmation email.
When a customer makes an EFT payment through their bank website, they have the opportunity to insert a reference to accompany the payment. This is a string of text.
We'd like to send the order number in the order confirmation email, so the customer can use the order number as the EFT reference, so the client site can match EFT payments and orders.
**How do we insert the order number into the order confirmation email?** | In the wp-e-commerce admin, Settings -> Store -> Admin, you can customise the Customer Purchase Receipt (confirmation email) template to add this, e.g.
`Please quote %purchase_id% as reference when paying by EFT.`
There are a couple of hooks in wp-e-commerce that let you insert other data into the confirmation emails:
* wpsc_transaction_result_cart_item -- this is called for each item in the cart array
* wpsc_transaction_result_message -- this is called to filter the text of the email
* wpsc_transaction_result_message_html -- this is called to filter the on-page confirmation
You can get more information about the whole deal on a blog post I wrote a while ago (NB: pre-3.8.9 which changed things slightly!) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin wp e commerce"
} |
Make compatible custom menu widget for Twitter Bootstrap
If I configure `wp_nav_menu` function, I can put the "items_wrap" option to achieve a nice navigation given by Twitter Bootstrap, thus: `<ul class="nav nav-pills">%3$s</ul>`. But, how to configure the custom menu widget to do the same? I mean, for achieve `<ul class="nav nav-tabs nav-stacked">%3$s</ul>` in all custom menu widgets, by default.
Thanks for help! Have a nice day. | Filter `'wp_nav_menu_args'`.
add_filter( 'wp_nav_menu_args', 'wpse_79901_nav_menu' );
function wpse_79901_nav_menu( $args )
{
$args['items_wrap'] = '<ul class="nav nav-pills">%3$s</ul>';
return $args;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "menus, widgets, navigation, twitter bootstrap"
} |
What difference does it make including the @package annotation or not?
I am somewhat familiar with the concept of packages in Java, but I'm new to Wordpress and PHP.
In a template file such as `header.php`, what is happening when you include the `@package` notation?
<?php
/*
* @package MyTheme
*/ | Those are PHPDoc tags. They are entirely for code documentation purposes. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "php"
} |
Alert Message through email or phone(Message)
Hi all I am newbie I need to know how to alert email or message while attempt login if success or if failure .That alert mail describe that login IP and date and time .
Is it possible to do this following in wordpress.
Thanks In Advance. | Successful log-ins trigger the action `wp_login`, failures `wp_login_failed`. Phone calls are not built-in, you need a separate plugin for that.
Example with email:
add_action( 'wp_login_failed', 'wpse_79917_login_failed' );
add_action( 'wp_login', 'wpse_79917_login_success', 10, 2 );
function wpse_79917_login_failed( $username )
{
wp_mail(
get_option( 'admin_email'),
'Login failed',
'custom message'
);
}
function wpse_79917_login_success( $user_login, $user )
{
wp_mail(
get_option( 'admin_email'),
'Login successful',
'custom message'
);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "login, wp login form"
} |
How to trigger a login form notice message?
How can I trigger a message box to appear on the login form?
I'l trying to get the little yellow notice bar to appear above the login form conditionally.
The below code only print the content on the page (duh, I know).
add_action('login_head', 'login_form_message');
function login_form_message() {
echo 'Custom Login Form Message';
} | There's a filter to add messages there. You can sneak in messages that will than handled like an error message (without being one).
apply_filters( 'login_message', $message );
Here's an example of this filter:
function wpse79920_login_msg( $message )
{
return 'Hello User!';
}
add_filter( 'login_message', 'wpse79920_login_msg' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp login form"
} |
How to add to a user_meta field (append)
Is this possible? I want to use Gravity Forms or another hook to somehow write to the END of a user_meta field - not overwrite it.
For example...
Before:
$purchase_history = get_the_author_meta('purchase_history', $user->ID);
echo $purchase_history; ('Concert in the Park 01/12/2004')
After:
echo $purchase_history; ('Concert in the Park 01/12/2004', 'Pancake Breakfast 05/15/2005')
Any ideas? Thanks. | Use `get_user_meta()`:
$original = get_user_meta(
$user->ID,
'purchase_history',
TRUE
);
echo $original . ' Pancake Breakfast 05/15/2005';
To update the value use `update_user_meta()`:
update_user_meta(
$user->ID,
'purchase_history',
$original . 'Pancake Breakfast 05/15/2005'
); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "user meta, plugin gravity forms"
} |
Filter categories using tags
I have a website with the following categories:
* Videos
* Pictures
* Stories
And I have a lot of tags like: `Funny`, `Awesome`, `Mind Blowing`, `Crazy`, etc.
Is there a way I could filter lets say: `Videos` tagged as `Crazy`?
I know you can do:
But that would retrieve ALL content tagged as `crazy`, I just want `Videos`.
I've searched the WordPress documentation without luck. | Another way that @toscho's solution made me try, and worked for me, is this scheme:
| stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "categories, filters, tags"
} |
How to update post parent?
I have an array of image id's and i want assign them to the specific post:
foreach ($image_ids as $image_id)
var_dump(wp_insert_post(array('ID' => $image_id, 'post_parent' => $new_post_id), TRUE));
But there occurs error:
object(WP_Error)#252 (2) {
["errors"]=>
array(1) {
["empty_content"]=>
array(1) {
[0]=>
string(38) "Content, title, and excerpt are empty."
}
}
["error_data"]=>
array(0) {
}
}
So is it possible to update the `post_parent` without updating other data? | Use `wp_update_post()`, not `insert`.
wp_update_post(
array(
'ID' => $image_id,
'post_parent' => $new_post_id
)
); | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 1,
"tags": "wp insert post"
} |
dynamic enquiry form
I'm thinking to use **Contact Form 7** to create a simple enquiry form like : name, phone, email.
This enquiry form will be displayed on every portfolio page.
What I want to do is to retrieve also from the user the page title from where he submitted the enquiry, because I will have more than 50 posts and I don't want to create 50 different forms for each post.
Any suggestions on how to achieve this ? Thank you! | Add a hidden field to the form like this:
<input type="hidden" name="page_title" value="<?php the_title_attribute(); ?>" />
This will send the current posts’s title. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, plugin recommendation, forms"
} |
Remove [gallery] shortcode altogether
I used remove_shortcode('gallery'); ...the gallery is gone, but the shortcode is visible in the text. How do I remove sitewide? I've searched for sql queries, but no solution fixes my specific problem.
!gallery shortcode still visible | The short code is actually entered into then page or post content so disabling the short code processing prevents the gallery short code from being replaced with the gallery images but it doesn't affect the post content.
The best solution is to add a new short code handler after removing the default gallery handles. Another less desirable approach would be to remove the short code tag from all posts and pages.
Short code replacement would look something like this:
function no_gallery($atts) {
return "";
}
add_shortcode('gallery', 'no_gallery'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "query, gallery"
} |
How to make WordPress use protocol indepentent upload files?
I am using `FORCE_SSL_ADMIN` in `wp-config.php` so everytime I upload a new image and inserted into the post, it is using SSL version
e.g.
<img src=" ..
My blog is using HTTP in the public side, so how to make the upload path as rotocol independent, e.g.
<img src="//www.example.com/wp-content/uploads/2013/01/test.png" .. | You can define a function to remove the protocol and hook it to the attachment URL:
function wpse_79958_remove_protocol_from_attachment($url) {
$url = str_replace(array('http:', 'https:'), '', $url);
return $url;
}
add_filter( 'attachment_link', 'wpse_79958_remove_protocol_from_attachment' );
Also consider to use relative URLs for attachments by using WordPress builtin function `wp_make_link_relative`:
add_filter( 'attachment_link', 'wp_make_link_relative' );
Place this code to your `functions.php`. Not tested though.
**Update** : already tested | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 4,
"tags": "plugins, images, uploads, urls, media"
} |
Show only if x comments?
Is there any function that will show some content only if there are more than x comments ? For example show some banner only if more than 10 comments are in post ? Thanks :) | `wp_count_comments()` returns the number of comments either for the whole blog or just for the current post.
Example:
if ( 10 < wp_count_comments( get_the_ID() )->approved )
echo 'Wow, more than 10 comments!'; | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "comments"
} |
Display tags in list without link
This seems like it should be something that's really simple to do, however it's apparently not.
I don't want tags to be links, but I want them to display in an unordered list, with each tag inside an `<li>`
get_the_tags allows you to echo them without the associated link, but I have no idea how to wrap them in li's.
<?php
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
}
?> | This would do it...
<?php
$posttags = get_the_tags();
if ($posttags) {
echo '<ul>';
foreach($posttags as $tag) {
echo '<li>' .$tag->name. '</li>';
}
echo '</ul>';
}
?> | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "tags, lists"
} |
Default permalink structure causing Notice: Undefined property: WP_Query::$post
I use the wp for membership site. I use pages for the user log in, manage post, edit profile and etc.
When I apply the default permalink structure, I found that the debug mode show this notice on every pages (not post page).
Notice: Undefined property: WP_Query::$post in /var/www/example/wp-includes/query.php on line 2986 Notice: Trying to get property of non-object in /var/www/example/wp-includes/query.php on line 3349
But when I use the post name for the permalink structure, this notice disappeared.
Though it seems is not a serious issue (is it?), but I'd to know what causing this warning?
Thanks | Finally I found what causing this problem, turns out it have to do with my **pre_get_post** hook. Because I using **is_page** to check the specific page, which is not appropriate.
Here is what I did
function check_page($wp_query){
if($wp_query->is_page(array('1','2','3')) ){
//do something here
}
return $wp_query;
}
add_action( 'pre_get_posts', 'check_page' );
So my solution to this is:
function check_page($wp_query){
$pageidarray = array('1','2','3');
if($wp_query->is_page() && in_array($wp_query->query_vars['page_id'], $pageidarray) ){
//do something here
}
return $wp_query;
}
add_action( 'pre_get_posts', 'check_page' );
Problem solved. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query, permalinks"
} |
How to show the homepage on a different url, like site.com/blog instead of site.com?
I have Wordpress installed in my root directory, so if you go to site.com you see the list of recent posts.
What I want to do is to have the homepage show a static page instead showing recent news etc (I've figured out how to do this), however if someone goes to site.com/blog/, I want to show a list of the recent posts the same way as they show up right now on the homepage.
Can I do this - if so, how?
P.S the other url doesn't have to be called /blog/, it can be anything, e.g site.com/recent/ or site.com/archive/ would also work.
Thanks. | Create a simple page which is needed to be the homepage and another page on which you want to show your recent blog posts.
Then go to Settings > reading and set _a static page_ option in front page displays option. Then for the front page select box, select the new homepage and for the post page select box, select the custom page on which you want to display all your post listings. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "permalinks, urls, homepage, home url"
} |
How to structure Multisite sites into categories?
When using WordPress Multisite with many sites, it would be nice to store them into categories. Site categories that is, not post categories.
Maybe there is a way to use some kind of site meta / custom fields for sites? Is there one? How to use it?
A plugin would be nice, or an example of a start, what hooks / functions to use. | Answering to this Question, How to add Custom Blog Options to new blog setup form?, I ended up doing a plugin that does exactly that: adds a blog meta field to give each site a Category.
It's a simple meta field, meaning: no category tree. I just revised the code and updated. Available in GitHub.
Main hooks:
* `add_signup_meta`
* `signup_blogform`
* `wpmu_new_blog`
!multisite categories | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, custom field, multisite"
} |
How to create a template for Pages?
In Wordpress, when creating a page, it shows some options for Template under Attributes, such as: Default, Links, One column no sidebar, etc.
Is there a way to add more custom templates to show up here? If so, how? | All you need to do is just create a new file in your theme root directory. This file must start with following code:
<?php
/**
* Template Name: No Sidebars
*/
Name your file, for example, `page_nosidebars.php` and then WP will add `No Sidebars` template to available templates list.
There is nice article about it Creating Custom Page Templates. I think it will help you to create your own. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "posts, theme development, templates, page template"
} |
Jetpack could not contact wordpress
I recently created a site and installed Jetpack and activated it, but it gives me the following error:
> Jetpack could not contact WordPress.com: register_http_request_failed. This usually means something is incorrectly configured on your web host. Failed to connect to 76.74.254.123: Permission denied | I was receiving an error similar to this on one of my past sites. Turned out that my host was blocking XML-RPC requests to remote servers. My solution: switch hosts (unless you're running on a VPS where you can configure your server). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "errors, plugin jetpack"
} |
Display random post on a page with post permalink in URL
I have seen many snippets to display random post/posts on a page. Most of them provide a function or wp_query code to be directly placed where it is required. In the end they tell to create a template random.php and page with name RANDOM. So, when one wants to access that page, they can look for a link pointing as < And every time, I find the same URL --> What I want is to display the URL of the post i.e permalink in the address bar, whenever one clicks on random page link e.g post-permalink. I use this piece of code.
query_posts(array(
'showposts' => 1,
'orderby' => 'rand',
));
if (have_posts()) : while (have_posts()) : the_post();
I don't know much about using 'base' and 'format' arguments in the array, they might serve purpose.
Thanks | What you are asking is how to redirect the visitor to a random post. Here you go:
<?php
/*
* Template Name: Random Redirect
*/
query_posts(
array(
'showposts' => 1,
'orderby' => 'rand',
)
);
if (have_posts()) : while (have_posts()) : the_post();
header( 'Location: ' . get_the_permalink() , false , 303 );
The syntax is
void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
... and the 303 status code denominates «See other». | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "query posts"
} |
Give each post type label a different color?
On my homepage I am using a code to call different post type labels. Example:
> TV Series: "Once Upon A Time"
Here is the code I use to call the label:
<a href="<?php echo get_post_type( $post->ID ); ?>">
<?php $post_type = get_post_type_object( get_post_type( $post ) );
echo $post_type->label; ?>
</a>
I want to place each post type in a div with different background colors. Example:
!Example
Do you see how once upon a time has a different background from pretty little liars? I also want to be able to make the link color different. | You can do something like this:
<a href="<?php echo get_post_type( $post->ID ); ?>" class="<?php echo str_replace(' ', '-', get_post_type( $post->ID )); ?>">
<?php $post_type = get_post_type_object( get_post_type($post) ); echo $post_type->label ; ?>
</a>
and in your **CSS** part you can do something like:
.pretty-little-liars
{
background color: khaki;
}
.once-upon-a-time
{
background color: blue;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, css, labels"
} |
Remove permalink from images when inserting into post
In previous versions of WP, we were able to remove permalink from images while we were inserting images into post.
But now there is no obvious option to do so. How can it be achieved? | When you insert an image to the post you see `Add media` modal dialog. It has a field named `Link URL` with three buttons underneath, including `None` to remove the link.
_Screenshot_ :
!enter image description here | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "posts, permalinks, images, visual editor"
} |
What is wrong with this code to remove wp admin bar from one page
I'm just trying to turn off the wp admin bar on one page, but this function removes it from every page. What am I missing?
<?php
if ( !is_page('image-upload') ):
show_admin_bar(false);
endif;
?> | You need to remove the (!) infront of the conditional, you can read about PHP-operators here.
Now you simply say that if not on page "image-upload" remove the admin_bar.. Here is the working code:
<?php
function wpse_80018_hide_admin_bar() {
// If is on page "image-upload"
// Remove the admin_bar
if ( is_page('image-upload') ):
show_admin_bar(false);
endif;
}
add_action('wp_head', 'wpse_80018_hide_admin_bar');
?>
Just an example to understand the conditional:
<?php
function wpse_80018_test() {
// If iam on page "image-upload"
// Echo honey i'm home!
// If on another page echo "Working on another page!"
if ( is_page('image-upload') ) {
echo "Honey i'm home!";
} else {
echo "Working on another page!";
}
}
add_action('wp_head', 'wpse_80018_test');
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin"
} |
Remove custom taxonomy column from my custom post type columns
I am using wp 3.5 i have a custom post `(sp_product)` and also i have custom taxonomy. I want to remove that custom taxonomy filter column but i don't want to make `'show_admin_column' => false`.
I wanna unset from `$columns['']` .
How should i do that ? i also want to add some css/js when it will show in column and top select menu. (showing in this image like) | function wpse_80027_manage_columns($columns) {
// remove taxonomy column
unset($columns['taxonomy-YOUR_TAXONOMY_NAME']); // prepend taxonomy name with 'taxonomy-'
// add your custom column
$columns['CUSTOM_COLUMN_NAME'] = __('Column Name');
return $columns;
}
add_filter('manage_edit-sp_product_columns', 'wpse_80027_manage_columns');
function wpse_80027_add_img_column($name) {
if('CUSTOM_COLUMN_NAME' == $name) {
// echo your image in 'CUSTOM_COLUMN_NAME' column
echo '<img src="image-name.png />';
}
}
add_action('manage_sp_product_posts_custom_column', 'wpse_80027_add_img_column'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom taxonomy, filters, columns"
} |
How is WooCommerce cart.php template supposed to be used?
I have a fresh install of Wordpress 3.5 and WooCommerce 1.6.6 (WC from now on) and use the default Twenty Twelve theme.
I added a Product to WC and when viewing that product and using the Debug Bar Template Trace plug-in I can see that the template `woocommerce/templates/single-product.php` is used. However, if I view the Cart page, which was automatically generated by WooCommerce, it uses the `twentytwelve/page.php` template and not the `woocommerce/templates/cart/cart.php` template, which I found surprising.
I'm a little confused from this outcome. Isn't the `cart.php` template supposed to be used for the Cart page? If not, what is that template for, and under which circumstances does it get used by WC? | Comparing the markup generated by `page.php` when the cart is displayed, it seems that the content is generated by `cart.php`, similarly to loading a template part, so `cart.php` is actually used whenever the cart is displayed. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "templates, plugins"
} |
Filter taxonomy terms using multiple id in the edit-tags.php
I want to use the edit-tags.php search function with multiple term id's. For example, if i type into the searchbox something like this: #1245&6832, it should display these two terms in the results table(WP_Terms_List_Table).
I tried to use the pre_get_posts action to get access to the query that is running for the search, but this is just showing me an "empty" query:
add_action('pre_get_posts', 'filter_terms_by_ids' );
function filter_terms_by_ids( $wp_query ) {
global $pagenow;
if($pagenow == 'edit-tags.php' && $_GET['s']):
print_r($wp_query->query_vars);
endif;
}
My idea is to check the $_GET['s'] and if # is the first character, i can modify the query to only include these terms in the search:
if ('#' == substr($_GET['s'],0,1)) | It's easy to implement. All you need is your own hook for `get_terms_args` filter:
add_filter( 'get_terms_args', 'wpse8170_get_terms_args', 10, 2 );
function wpse8170_get_terms_args( $args, $taxonomies ) {
if ( !in_array( 'post_tag', $taxonomies ) ) {
return $args;
}
$matches = array();
if ( empty( $args['search'] ) || !preg_match( '/^\#(.*)$/', $args['search'], $matches ) ) {
return $args;
}
if ( count( $matches ) == 2 ) {
$args['search'] = '';
$args['include'] = array_filter( array_map( 'intval', explode( '&', $matches[1] ) ) );
}
return $args;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "taxonomy, search, terms"
} |
How do I remove a category from a wordpress loop>
I have a question. I need to have, in my archive.php file, a exclusion of a specific category. given what I have now, how would I make that happen?
Here is the code:
<?php
query_posts(array(
'post_type' => 'post',
'showposts' => 5
) );
?>
<?php while (have_posts()) : the_post(); ?>
<div class="blogcontentlinks">
<a style="text-decoration:none;" href="<?php the_permalink() ?>"><h2><?php the_title(); ?></h2></a>
<p style="">Posted on <?php the_time('m/j/y g:i A') ?><br />Categories: <?php the_category(' ') ?><br />Tags: <?php the_tags(' ') ?></p>
<p><?php the_excerpt(); ?></p>
<p> </p>
</div>
<?php endwhile;?>
Thank you | You can add `category id` or `category slug` into arguments you are passing to `query_posts`:
<?php
// category slug ('products')
query_posts(array(
'post_type' => 'post',
'showposts' => 5,
'category_name' => 'products'
) );
?>
or
<?php
// category id ('3')
query_posts(array(
'post_type' => 'post',
'showposts' => 5,
'cat' => '3'
) );
?>
In the second case you can use comma separated list of category ids like `'cat' => '3,5,7'`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, categories, loop, archives, exclude"
} |
Create custom taxonomy and Display in metabox dropdown
I'm looking to create a dropdown in the post edit screen which contains 3 already existing tags. What's the easiest way of doing this?
Basically all I'm looking for is a simple drop down which adds one of the following tags to the post itself; 'beef-stew', 'pea-soup' & 'chili'. I'd also like 'beef-stew' to be the default.
Thank you in advance
EDIT: As I don't want the user to be able to display more than 1 of these 3 categories at any time, and have to option to easily change which one as they please, tags might not be the best solution? Would I be better off creating a custom taxonomy ('food')? They will basically be used to change the way a post is displayed on the front page of the website. | I followed this handy guide and it worked a treat:
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom taxonomy, metabox, taxonomy, tags, dropdown"
} |
Woocommerce product categories order
Is it possible to sort product categories?
I have a category with a lot of subcategories. On the category page all the subcategories is listed. Right now I can only change the order by drag and drop in the admin panel. But that is very time consuming with a lot of categories. Any way to change the order without using drag and drop? | Woocommerce stores 'order' metakeys in the table `wp_woocommerce_termmeta`. The mechanism it uses is the same as `menu_order` for posts.
Something like this should work:
$terms = get_terms('product_cat');
//sort $terms somehow
$i = -1;
foreach ($terms as $term) {
$i++;
update_woocommerce_term_meta( $term->id, 'order', $i);
}
The same procedure can be used to sort other Woocommerce taxonomies such as `product_tag` and **Product Attributes**. For a Product Attribute named Size, the taxonomy would be `pa_size`, and you should replace 'order' by `order_pa_size` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "categories, plugins"
} |
How do I test my localhost WordPress project with VirtualBoxVM?
I'm working on a WordPress project set up with MAMP on localhost. I try testing the site on internet explorer with VirtualBoxVM by browsing to my local ip. My problem is, wp_head() outputs absolute path's to css and js resources, so the VirtualBoxVM Browser tries to load which will, of course, fail.
How do I get VirtualBoxVM to load these resources properly?
Maybe I can make the resource urls relative? | If I understand you, don't use 'localhost'. That only works if you are testing from the same machine that is running the server. (A virtualized machine counts as a different machine.) Give your server (the machine running the server) a static IP address-- something like 192.168.1.5-- and use that instead of 'localhost'. That will work for any machine on your subnet. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "urls, localhost, wp head, paths, ip"
} |
Display custom field value on woocommerce product page
I know similar questions have been asked dozens of times but I'm just not understanding how to display custom fields. I'm using woocommerce and want to display a custom field value on product pages.
I add the custom field "current_promotions" and a value to a product, and have tried adding this to the content-product.php template, but I'm getting nowhere:
<?php $postid = get_the_ID(); ?>
<?php get_post_meta($post_id, $key, $single); ?> | This should do it
<?php echo get_post_meta( get_the_ID(), 'current_promotions', true ); ?> | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 4,
"tags": "custom field, plugins"
} |
How WP decide to show or not to show in admin panel the pop-up window with hint? Need a fix
To all newcommers the WP3.5 show the floating hint about new abilities of 3.5 version placed on top left coner of screen saying:
**We 've combined the admin bar and the old Dashboard header into one persistent toolbar. Hover over the toolbar items to see what's new. {close}**
after close-click the hint disapeared for good. And this was my case. but after use of Search&Replace plugin on my mysql database i got this banner again, and this time it is not clicable and still atached to top left corner unless i change screen for other wordpress activity i.e. apearance or something other than initial dashboard. I wonder where i do look for fix in database? I joined a screenshot of this banner (ru_RU)
WP3.5 non-removable hint | Dismissed pointers are stored as user meta, you can inspect this for yourself with:
$meta = get_user_meta( wp_get_current_user() );
print_r( $meta['dismissed_wp_pointers'] );
In your case, the meta might be empty or damaged, to update dismissed pointers for ALL users on your blog, you could run this function (only once):
function wpse80084_dismiss_wp_pointers()
{
$dismissed = array( 'wp330_toolbar','wp330_media_uploader','wp330_saving_widgets','wp340_choose_image_from_library' );
$dismissed = implode( ',', $dismissed );
$users = get_users();
foreach ( $users as $user )
update_user_meta( $user->ID, 'dismissed_wp_pointers', $dismissed );
}
add_action( 'admin_init', 'wpse80084_dismiss_wp_pointers' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, dashboard"
} |
Enable Recent Comments widget to display comments on attachment posts
Is it possible to hook into the default Recent Comments widget to enable it to display comments for attachment posts? If so, how? | you can use the `widget_comments_args` filter to modify the default args of the recent comments widget:
function wpse80087_widget_comments_args( $args )
{
$args = array( 'number' => 5, 'post_type' => 'attachment', 'status' => 'approve', 'post_status' => 'inherit' );
return $args;
}
add_filter( 'widget_comments_args', 'wpse80087_widget_comments_args', 10, 1 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments"
} |
How to make posts being uncategorized
I have some posts which do not have any category, by default, wordpress shows them under "Un categorized". Is there any way to stop this? I want those posts under the categories I have in **metabox title** (list of categories for meta tag, if I select some category, from metabox title, it should come under the selected categories from metabox title). But it saves the posts under "Un categorized" | All posts have to be associated with at least one category. It might be possible to bypass this requirement but probably doesn't worth the effort.
If you really need to be able to have content without categories then you should create and use a custom post type, with which you can create and use custom taxonomies. It is hard to understand from the question what are you doing with the meta values but it sounds like you are trying to recreate the functionality of custom taxonomies. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, categories"
} |
Make videos output as iframes not links
is there any way to change the default output when inserting a video into tinyMCE with Wordpress' default media manager. Currently it inserts it as a link, would it be possible to input it into the editor as an iFrame with all attributes intact.
Thanks in advance! | Copy paste from my answer here but with iframe/video mime type added:
Alter image output in content
function WPSE_80145_Mime($html, $id) {
//fetching attachment by post $id
$attachment = get_post($id);
$mime_type = $attachment->post_mime_type;
//get an valid array of video types, add any extra ones you need
$image_exts = array( 'video/mpeg', 'video/mp4', 'video/quicktime' );
//checking the above mime-type
if (in_array($mime_type, $image_exts)) {
// the image link would be great
$src = wp_get_attachment_url( $id );
// enter you custom output here,
//you will want to change this to what you want in the iframe
$html = '<iframe><a href="' . $src . '"></a></iframe>';
return $html; // return new iframe wrapped video via $html
}
return $html;
}
add_filter('media_send_to_editor', 'WPSE_80145_Mime', 20, 2); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tinymce, videos"
} |
How to add a post class on every post. (on homepage)
I have this code in my home.php, the very first post class does not get the class while the others do. Same thing when i move this code to functions.php. I get php errors when i remove the hook around it and just add the filter.
add_action('pre_get_posts', 'theme_add_post_class');
function theme_add_post_class() {
/** Add custom post class */
add_filter( 'post_class', function( $classes ) {
$classes[] = 'span4';
return $classes;
} );
}
} | function wpse80148_filter_post_class( $classes ) {
if( is_home() || is_front_page() )
$classes[] = 'span4';
return $classes;
}
add_filter( 'post_class', 'wpse80148_filter_post_class' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, theme development"
} |
How to exlude posts that have certain meta_value?
I want to exclude some posts from the home page. So I want to use meta data, and filter all posts that are signed by meta_value=0. Like this:
$args = array(
'posts_per_page'=>28,
'meta_query' => array(
array(
'key' => 'show_on_home',
'value' => '0',
'compare' => 'NOT LIKE'
)
)
);
$query = new WP_Query( $args );
So, if I sign some post with meta_key=0 it will not apear.
The problem is that I have a lot off posts that don't have meta data at all, and I don't want to filter them. | WordPress 3.5 and up supports `EXISTS` and `NOT EXISTS` comparison operators.
> compare (string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' (only in WP >= 3.5), and 'NOT EXISTS' (also only in WP >= 3.5). Default value is '='.
>
> <
So...
array(
'key' => 'show_on_home',
'compare' => 'NOT EXISTS'
)
... should show all posts that don't have that key. I think that is what you are trying to do. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "meta query"
} |
How to order categories in Woocommerce that are spread over multiple pages?
I'm building a store using Woocommerce and need to manage a large number of product categories.
I would like to re-order them to appear in alphabetical order. However the drag and drop ordering system splits categories over several pages and I can't seem to find a way of editing the entire list rather or move items from one page to another.
Is there any way I can do this? If so how is it done?
Thanks. | Under screen options on the Product Categories page, change the number of product categories to something big enough to get job done; drag and drop to order; change back to 20 or something manageable. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "categories, plugins"
} |
How can I add a jQuery OnClick event to the Publish posts button?
I want to add a simple confirmation event to the Publish posts button, so when my client hits "Publish" it will ask him if he's sure, to which he clicks "Yes" or "cancel" and the post then publishes or doesn't.
I'm new to WordPress...or at least I've only done theme and limited plugin programming. I did find the metabox code for the "Publish" button in `edit-form-advanced.php`:
add_meta_box('submitdiv', __('Publish'), 'post_submit_meta_box', null, 'side', 'core');
But to accomplish this, I suspect I'll need to add the jQuery code elsewhere - preferably in my theme.
For site-specific reasons, I cannot add new plugins to this installation so any changes need to be confined to my theme's `functions.php` file. | You can hook into the post footer actions (based on this answer, not tested):
add_action( 'admin_footer-post-new.php', 'wpse_80215_script' );
add_action( 'admin_footer-post.php', 'wpse_80215_script' );
function wpse_80215_script()
{
if ( 'post' !== $GLOBALS['post_type'] )
return;
?>
<script>
document.getElementById("publish").onclick = function() {
if ( confirm( "Ready?" ) )
return true;
return false;
}</script>
<?php
}
These actions are called in `wp-admin/admin-footer.php`:
do_action( "admin_footer-" . $GLOBALS['hook_suffix'] );
This code can be used in a plugin (preferred) or in your theme’s `functions.php`.
See also:
* Where to put my code: plugin or functions.php?
* Where do I put the code snippets I found here or somewhere else on the web? | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "jquery, publish"
} |
Change Rating range in Link Manager
I have looked in here and across the internet but I can not seem to find an answer. Is there a way to change the values of the ratings. By Default it seems to be 0 to 10, but I can not find a way to modify this feature to something like 0 to 20 or something.
Thanks. | See the function `link_advanced_meta_box()` in `wp-admin/includes/meta-boxes.php`:
<td><select name="link_rating" id="link_rating" size="1">
<?php
for ( $r = 0; $r <= 10; $r++ ) {
echo '<option value="' . $r . '"';
if ( isset($link->link_rating) && $link->link_rating == $r )
echo ' selected="selected"';
echo('>' . $r . '</option>');
}
?></select> <?php _e('(Leave at 0 for no rating.)') ?>
The value is hard-coded.
You could deregister the metabox `'linkadvanceddiv'` and register your own instead.
Be aware the link manager has no future. I would use a custom post type instead with specialized meta data handling. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "functions, links, rating"
} |
Undefined function wp_set_password
I'm creating a plugin. I'm receiving the following error (WP 3.5):
Fatal error: Call to undefined function wp_set_password() in \path\to\plugin.php on line 18
Line 18 consists of simply:
wp_set_password( 'newpass', $user_id );
This is located in the main plugin file, and all other code has been commented out in order to try and seclude this error. I have no idea why it's showing up as undefined.
Am I missing something here?: <
Thanks | When your plugin loads, pluggable functions aren't loaded yet, in fact a lot of stuff is not loaded yet, this what actions are for. Hook your function to an action, like `plugins_loaded` or `init`, when the WP environment is loaded and initialized:
add_action( 'init', 'wpa80246_init' );
function wpa80246_init(){
wp_set_password( 'newpass', $user_id );
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugin development, functions"
} |
Where are available Roles Defined in the wp_ database?
I got on the list to test a private beta of a plugin I'm using on a multisite network.
The plugin authors have code in there to add a custom role. They have a bug that removes the ability to give a user any role except their one custom role.
When I visit `../wp-admin/network/site-users.php`, the "Add User" role pulldowns only show the one role this plugin added. The change role pulldown menu shows all the WP default roles, plus a few extra roles this and other plugins have added. If I attempt to change a user to one of these roles, I get a "You can't give users that role" error page.
I've been discussing this with the developer, and they seem baffled.
I've been looking through my database and the codex, and I can't find where the valid roles are defined. | User roles are stored in `wp_options` table.
search for option name `wp_user_roles` in the `wp_options` table. | stackexchange-wordpress | {
"answer_score": 45,
"question_score": 26,
"tags": "multisite, user roles"
} |
Transform php code into a widget?
how can I create a widget out of a php code? It's just a disqus code that I would like to place in the sidebar. I could just paste the code in the widget section (my tag), but then I would not be able to change it's order with the other wigets. This is why I want to convert this code into a widget. | Here is a stand-alone answer. Building a widget to echo hard-coded PHP is trivial.
class PHP_Widget_wpse_80256 extends WP_Widget {
function __construct() {
$opts = array(
'description' => 'Display Some Hard Coded PHP content'
);
parent::WP_Widget(
'my-hc-php-content',
'Some PHP',
$opts
);
}
function widget($args,$instance) {
// PHP goes here, like this:
echo 'PHP generated content';
}
}
function register_my_widgets() {
register_widget('PHP_Widget_wpse_80256');
}
add_action('widgets_init','register_my_widgets');
There is no need for the overhead of a plugin or the overhead of `eval`ing your widget text, which is what the plugin mentioned does. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "php, widgets"
} |
My theme is not showing up on any other computers
I have Wordpress installed to mydomain.org/blog, and everything works fine and dandy from my computer (localhost). However, when I connect to the blog from another computer, the theme (Twenty Twelve) disappears and it's all plaintext. I have not tried to install any other themes. Help?
Edit: URL upon request is < | What I had done was in the WordPress Admin page, under Settings > General, I had put `localhost/blog` for the `WordPress Address (URL)`. Changing this to the public URL of my site fixed the problem. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "theme twenty twelve"
} |
Single Post in Tab/Slider
I have managed to code tab system that fetches different categories and custom taxanomies on a home page and shows relative posts. Now, is it possible that when someone clicks on one of the posts in some specific tab, then the post's content can be shown in the tab itself, instead of taking the user to the single post (single post page)?
Here is the screenshot:
!enter image description here | If you are using jQuery UI Tabs you can use AJAX to load the content. There is an example on the plugin page.
UI Tabs is always part of a WordPress installation and registered already as `jquery-ui-tabs`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, homepage, single, tabs"
} |
Is there any other place - besides a theme, a plugin, or a mu-plugin - that an option page might conceivably be used?
I'm creating a helper class for simplifying the creation of an option page in admin that could conceivably be used in a theme, a plugin, or a mu-plugin. I'm trying to make the class as easy to instantiate as possible, so I plan on determining programmatically which of those three places the class is being instantiated from.
I haven't come across any other ways an option page might be desirable, but I don't want to leave out a scenario that I just haven't encountered or thought of. | Unless you are working on WordPress core development you should not be writing anything but a:
1. Theme
2. Child Theme
3. Plugin
4. Mu-Plugin
5. Drop-In
For the last two see: <
I am out on a limb a little bit here but I think that is the exhaustive list, with the first three by far the most common. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "options"
} |
Fixed layout for admin section
I would like to customize the layout of the admin section of WordPress.
The thing is, whatever the layout I create, I'm very dependent of the default "fluid" layout of the admin. By fluid, I mean: when I resize the browser window, things tend to reorganize themselves in the admin section (in order to optimize space) and while it's a nice feature with the default look and feel of the admin section, it's a real pain in the neck when you try to create your own custom layout.
Can someone tell me which css attributes of the admin need to be changed and what attributes parameters would disable that overall fluid behavior? | This is still to be confirmed but so far so good: What I did is open all the minified css related to the admin section and deleted theses parts
@media only screen and (max-width:xxx px){...}
whenever I found one.
It seems to work and doesn't mess with anything else, as far as I know. Of course, this only makes sense if you intend to re-layout the admin from scratch. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "admin, css, wp enqueue style"
} |
Custom Attachment Type
I want to create a "photography" custom post type which uses attachment's same edit/upload panel. Exact same panels usage for "attachment" post type but with "photography" name. Is it possible? | It seems its impossible with WordPress 3.5 at the moment. I opened an idea for it: < Support if you like idea please. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, wp admin, media library"
} |
Add an attachment feature to comments
Is there a way to allow attachments with wordpress comments?
I know of a paid plugin that allows this but I was hoping for someone to point me in the correct direction that's future proof and doesn't rely on plugins. Ideally I would want the attachment to be connected to the post itself so we could query all the attachments if needed.
Thanks! | Here is my suggestion:
Just download this Comment Images plugin.
As of now it only support images. But upload work with all file types.
So just make a little tweak like this. So it will display attachment link.
Replace line 245 from
$comment->comment_content .= '<img src="' . $comment_image['url'] . '" alt="" />';
to
$comment->comment_content .= '<a href="'. $comment_image['url'] .'">Download attachment</a>';
But you mentioned, you want that function in theme instead of plugin. So if you really know what you are doing, just integrate that whole plugin code in your theme by changing file path.
Otherwise, just hire a programmer. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, attachments"
} |
Need help "sanitizing" a custom function that pulls category slug into body class
Not sure if "sanitizing" is really the correct phrase to use for this but it was the best one I could think of...anyways, here is the problem:
My function works great like so...
// add category id to body & post classes
function category_id_class($classes) {
global $post;
foreach((get_the_category($post->ID)) as $category)
$classes [] = $category->cat_name;
return $classes;
}
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');
That works great until the user inputs a category such as "Category 1" with a _space_. Spaces are obviously not desirable as CSS classes so if we could maybe just have a dash added to replace the space that would be perfect - just not sure how to accomplish that?
Thanks! | Just use `$category->slug` instead of `$category->cat_name`. Slugs are already lowercase and with dashes instead of spaces. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, post class, categories"
} |
How to get the permanent link in a plugin?
I'm writing a plugin to add some extra contents that contain the permanent link to the (single) post.
function abcd_add_contents($content) {
$extra_content = the_permalink();
if (is_single()) {
$content .= $extra_content;
}
return $content;
}
add_filter('the_content', 'abcd_add_contents');
`the_permalink()` does not work. How can I obtain the permanent link information of the current post in this plugin function? | globalize `$post` to get the current post's data. also, you want `get_permalink`, which _returns_ the permalink, rather than `the_permalink`, which directly _echoes_ the permalink.
function abcd_add_contents($content) {
if (is_single()) {
global $post;
$extra_content = get_permalink( $post->ID );
$content .= $extra_content;
}
return $content;
}
add_filter('the_content', 'abcd_add_contents'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, plugin development, permalinks"
} |
Where have the Privacy Settings gone in WordPress 3.5?
I moved a WordPress site to another server and everything is working well, minus the fact that I can't seem to change the settings in Privacy. When I click on "allow search engines to index this site", the radio button automatically switches back to "ask search engines not to index this site". Also, the Privacy Settings menu itself is gone from the Settings menu. I have to manually type in `/wp-admin/options-privacy.php` to access the page. Can anyone tell me what is going on? | The _privacy_ page was removed in WordPress 3.5. Go to `wp-admin/options-reading.php` and set search engine visibility there. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "options"
} |
Initialize WordPress customizer variables
I have recently starting integrating the wordpress customizer into my theme.
Given the fact that i already had a theme options page, i use these values as default values of my new options (in the add_setting parameter).
All my new options are held into a variable called 'theme_options' which is an array of values.
The problem i have is that a user has to visit the customization page and click "save" on his first install to populate the 'theme_options' variable.
I am wondering if there is a way to initialize this field on theme activation directly (just like many theme options framework do).
Thanks in advance ! | I believe that all you need to do is pass defaults to `get_option`
function init_theme_options() {
// check to see if theme options are set
// Not sure how your options are organized but...
$defaults = array(
'opt1' => 'stuff1',
'opt2' => 'stuff2'
)
$theme_options = get_option('theme_option_name',$defaults);
}
If you want to see a very complicated version of this, look at how Twenty Eleven does it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme customizer"
} |
display shortcodes outside of the_content
Is there a way to display shortcode content outside of the_content?
I am building a custom theme who's theme options includes two text boxes that can be displayed on the front page. I want to be able to display shortcode content placed in these text box options. The theme uses files from the Options Framework. | You can use the function `do_shortcode()` for use shortcodes outside fomr default content. You can also parse this in your function, there get the output of your textfields, like the follow example for a custom field:
if ( get_post_meta( $post->ID, 'cfield', TRUE ) )
echo do_shortcode( get_post_meta( $post->ID, 'cfield', $single = TRUE ) ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "shortcode"
} |
Register a title automatically with a relationship field
I'm trying to optimize the code of my site . I wanted to know if it was possible to give automatically a title to a new post without having to do it manually. I have a website of video games. Before posting a review, I first need to create the plug of this game with all the information (publisher, developer, pc configuration etc.).. So I have to put twice the same title. I would only select the plug of the game without having to type the title of the game
To get the title, I am able to retrieve the ID of the plug. Do you think I can write a function?
Thank You
Code example for get the title of a game :
<?php foreach(get_field('fiche') as $post_object): ?>
<? echo get_the_title($post_object->ID); ?><br />
<? echo 'Genre' .get_field('genre', $post_object->ID); ?>
<? endforeach; ?> | If you can grab your data early enough you can do this:
function alter_title($t) {
return 'altered-title';
}
add_filter('pre_post_title','alter_title');
add_filter('pre_post_name','alter_title');
That will change the title and the slug before the post is saved. Of course, you need to work out some logic for that function. As is, it changes all post/page/CPT names and slugs on both save and edit. Probably not what you want... :)
That should work. Your game data should be in `$_POST`. If for some reason it doesn't you can run a function on `save_post` but you will need to push another write to the database.
There are a lot of hooks for post insert/edits so you may even find something more appropriate by browsing the source file. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, title, advanced custom fields"
} |
strange behavior with comment position
I've created a custom `content.php` and removed any comments on the `content.php` page
then i changed the `sharing-service.php` from jetpack and added `comments_popup_link` there:
// Wrapper
$sharing_content .= '<div class="sharedaddy sd-sharing-enabled">';
$sharing_content .= '<div class="robots-nocontent sd-block sd-social sd-social-' . $global['button_style'] . ' sd-sharing">';
if ( $global['sharing_label'] != '' )
$sharing_content .= '<h3 class="sd-title">'. comments_popup_link( __( 'Leave a reply', 'changed2012' ) , __( '1 Reply', 'changed2012' ), __( '% Replies', 'changed2012' ) ) . $global['sharing_label'] . '</h3>';
$sharing_content .= '<div class="sd-content"><ul>';
and it looks like this:
!comment position !enter image description here
does anyone have an idea why its getting moved there? and how i can move it back where it should be? | You could probably just buffer the output from comments_popup_link in a separate function.
function get_comments_popup_link( $zero = false, $one = false, $more = false, $css_class = '', $none = false ) {
ob_start();
comments_popup_link( $zero, $one, $more, $css_class, $none );
return ob_get_clean();
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "comments, plugin jetpack, theme twenty twelve"
} |
Action hook load_textdomain $domain variable
I use the `load_textdomain` action hook to list all active localization text domains with corresponding path to translation files.
function mo_location( $domain, $mofile ) {
if ( !is_array($GLOBALS['moloc']) )
$GLOBALS['moloc'] = array();
$GLOBALS['moloc'][$domain] = $mofile;
}
add_action( 'load_textdomain', 'mo_location', 10, 2 );
For some reason the `$domain` variable is not filled with a "default" text domain values. Does anybody know why? | The `default` text domain is registered in `wp_load.php` before plugins are loaded. See the function `wp_load_translations_early()`.
So when you register your action callback, the text domain has been loaded already.
For an alternative way to list all registered text domains see this answer: List of Default Translated Phrases. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "actions, localization, translation, textdomain"
} |
How can i retrieve default post per page value? from settings->reading. And total number of posts?
I want to retrieve the default value of Post per page (the value that is set in settings->reading.
I've looked around and so far I've only found ways to query it. problem is i dont want to change what was set i just want to retrieve it for pagination purposes. i thought of using `$something->post_count.`(i might be wrong but as i understand it returns the amount of posts displayed currently) but this could be wrong in some cases.
Also how can i get the total number of posts ? | It's saved in an option:
$default_posts_per_page = get_option( 'posts_per_page' );
Reference: get_option Parameters
You can see the keys and values of all available options by manually entering the admin url:
> /wp-admin/options.php
## Edit
Total number of posts:
global $wp_query;
$total_posts = $wp_query->post_count; | stackexchange-wordpress | {
"answer_score": 61,
"question_score": 31,
"tags": "wp query, pagination"
} |
get_permalink vs the_permalink
I am filtering the_permalink to return a custom structure
function append_query_string($url) {
$url_endpoint = get_permalink();
$url_endpoint = parse_url( $url_endpoint );
$url_endpoint = $url_endpoint['path'];
return '#!'. $url_endpoint;
}
add_filter('the_permalink', 'append_query_string');
the filter above returns
#!/theme-folder/name-of-article
I need to remove the leading #! form that url and I had tried using get_permalink but I have found that the filter does not filter get_pemalink. I have checked the codex and I cannot find a filter for get_permalink. Do you know of a way to filter it so that it will match the_permalink? I can't use the_permalink because it outputs the information to the screen and breaks layout. I can't seem to assign it to a variable either. | If we look at `get_permalink` in source, we'll see the various filters applied to this function.
For posts, it's `post_link`, for custom post types, it's `post_type_link`, for pages it's `page_link`, and attachments is `attachment_link`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "post meta"
} |
Retrieving data from specific multisite blog
I have a custom-built website which pulls data from WordPress.
I've included `wp-blog-header.php` in my page and it is all set, I can get my posts, featured image, titles, anything I want, wherever I want.
Now I'd like to add new languages to my website, so I've set up multisite so I can have one site for each language. How can I access information from a specific site? I'm using subfolder method, but there is no `example.com/sub/wp-blog-header.php` file to include!
Any Ideas on how to pull data of specific site on external pages? | You can use the `switch_to_blog()` function to switch the scope to a specific site and access data from that site:
require_once( '/path/to/wp-load.php' );
switch_to_blog( 3 );
$option = get_option( 'admin_email' );
restore_current_blog();
Also, you should use `wp-load.php` when using WordPress API in your own project, not `wp-blog-header.php` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "multisite"
} |
Wordpress login form script
I am looking for something very simple but I'm not quite sure how to achieve this. I have been researching for the past 2-3 hours and gathered a lot of useful information. However, my knowledge in both PHP and WordPress isn't enough to do this from scratch.
What I need is the following:
* When the user is **not** logged in, this HTML code should be displayed:
<a href="#">Login</a>
* When the user **is** logged in, the previous HTML code should be replaced with:
<span>Welcome, *username*</span>
<a href="actual-link-for-logging-out-the-user">Logout</a>
Could anyone please help me out. I'd really appreciate the help :)
Thanks | You're going to want to use the `is_user_logged_in()` conditional tag to handle this.
global $current_user;
get_currentuserinfo();
if ( is_user_logged_in() ) {
echo "<span>Welcome $current_user->user_login</span>".
"<a href='".wp_logout_url()."'>Logout</a>";
} else {
echo '<a href="#">Login</a>';
}
Other functions referenced: wp_logout_url() & get_currentuserinfo()
FYI, all of this could easily be found on Google or in the WordPress Codex. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "login"
} |
Blogroll/Lins Menu not visible in my backend?
well, i'm confused. I can't seem to find out why my "Links" Menu doesn't show up in my wordpress admin.
I have this in my `functions.php` file …
add_action( 'admin_menu', 'remove_links_menu' );
function remove_links_menu() {
remove_menu_page('themes.php'); // Appearance
remove_menu_page('tools.php'); // Tools
//remove_menu_page('link-manager.php'); // Links
//remove_menu_page('edit-comments.php'); // Comments
}
However it clearly says, that `link-manager.php` is not removed. If comment-out the entire action the `themes` and `tools` Menus are showing back up. However the link-manager is never visible.
Any ideas? | From the codex: "As of Version 3.5, the Links Manger and blogroll are hidden for new installs and any existing WordPress installs that do not have any links. If you are upgrading from a previous version of WordPress with any active links, the Links Manager will continue to function as normal. If you would like to restore the Links panel to your install you may download and install the Links Manager plugin." | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "links, blogroll"
} |
Change places custom fields with title field in post wp-admin
Is it possible to make custom fields at the top, when writing a new post in admin panel ?
Thank you. | function wpse81499_move_postcustom_to_top()
{
if( 'post' != get_current_screen()->id )
return;
?>
<script>
jQuery(document).ready(function(){
jQuery('#postcustom').prependTo('#titlediv');
});
</script>
<?php
}
add_action( 'admin_footer', 'wpse81499_move_postcustom_to_top' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts"
} |
Is there any way to have Featured Text, as opposed to Featured Image?
I need to have Featured Text displayed on my category page, as well as a Featured Image. The Featured Text can not be in the Post at all (just as a Featured Image is not in the Post).
Does anybody know of a plugin that already does this? I've looked around a fair bit and can't seem to find anything.
Many thanks. | I use the excerpt for this, as this is exactly what custom excerpt is for. The (custom/manual) excerpt could have been named "featured text", because that is also what it is.
This excerpt is not to be confused with an automatic excerpt production. This excerpt will be drawn form the x first word of the content, when the manual excerpt is empty.
To find the excerpt text box, enable it under Screen options on the edit page.
The ensure your theme is actually displaying the excerpt on archive pages. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, theme development"
} |
How to restore all items from trash
I have accidentally deleted a WP user. By deleting it, WP removed all the media files, pages etc.
I could retrieve pages and posts from trash. But I could not restore media items. Is there a way to restore all items from trash back? | When deleting a user, WordPress displays a warning that unless you attribute the user's posts to a new user, it's posts will be deleted and you cannot undo those deletions.
That means the only way to restore the posts and media is to restore a backup of the WordPress instance or database which you hopefully have. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "backup, trash"
} |
Wordpress custom post type with folder structure in slug
I have setup a custom post type with the slug "interview" and it is working fine. I am trying to change the slug to "magazine/interview" but I keep getting 404 errors when I try to access the posts that are already there. Is there any specific trick to set a slug with "/" characters in it? | Make sure to flush rewrite rules after changing the permalink structure, this can be done by visiting the `Settings > Permalinks` page in admin. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "posts, customization, slug"
} |
How to set global variable in functions.php
I want to be able to echo the URL of the featured image of a post and after looking some on the web I found the following which works fine when I put it in a loop in my front page template.
<?php $thumbSmall = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'small' );
$urlSmall = $thumbSmall['0']; ?>
<?php echo $urlSmall; ?>
However, want to use variable $urlSmall in other places than in the front page template, and this is where my limited coding skills let me down. I tried to just copy paste
wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'small' );
$urlSmall = $thumbSmall['0'];
into my functions.php but that did not work. I need these variables to be globally recognized. What do I do here? write some kind of function? | You can turn your snippet into a function that returns the post thumbnail URL of a post:
function wpse81577_get_small_thumb_url( $post_id ) {
$thumbSmall = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'small' );
return $thumbSmall['0'];
}
Usage, supplying the ID of a post:
<?php echo wpse81577_get_small_thumb_url( 59 ); ?> | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 3,
"tags": "urls, thumbnails, variables, globals"
} |
Limit one submission from each user using Contact Form 7?
I am using Contact Form 7 along with the add-on Contact Form 7 Dynamic Text Extension to pre-populate usernames and emails.
I know this may be sort of a strange request but I want to be able to limit the number of submissions to one for each user only for one of my forms. Basically, it's a submission form for a contest and I don't want users to be able to submit over and over again.
Is something like this possible with this plugin? | Contact Form 7 does not save form submissions to a database, so you have no saved previous form submissions to check a current submission against.
That means you'll need to have a plugin that can save entries to a database (the plugin author seems to recommend "Flamingo" for that). Once you've got those, you'll need to figure out how to check each submission against the database unless that function's built-in to the new plugin you install.
Some plugins like Gravity Forms (paid, but I highly recommend it) include this functionality built in. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin contact form 7"
} |
Change the title of an Administration Panel
I'm working with a Lucidpress theme at the moment. A client has asked that the "Lucidpress Options" title of a metabox on the page editor screen be changed. I have searched through the Lucidpress theme and have not found anywhere to change the title.
Does anyone know, offhand, where to find this? Can anyone at least tell me what sort of a function I would be looking for? Could I do something similar to this: Change The Title Of a Meta Box ?
Cheers! | Look for `add_meta_box` or `grep` the Lucidbox directory for the metabox title-- "Lucidpress Options". It shouldn't be too hard to find. As I don't use that theme, or any other publicly released theme, I don't know what else to say to you. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "metabox"
} |
How to determine the depth of a term in a custom taxonomy?
I'm building a `<select>` dropdown to display a list of terms for a custom hierarchical taxonomy. How do I know the depth of each term? I'd like to add some indentation for child-terms (the more deeply they're nested, the more indentation there should be).
However I'm not able to retrieve the depth level from `get_terms()`. How to get the depth level as an integer? | You can use wp_dropdown_categories():
> Display or retrieve the HTML dropdown list of categories.
$args = array(
'show_count' => 1,
'hierarchical' => 1,
'taxonomy' => 'my_taxonomy',
);
wp_dropdown_categories( $args ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom taxonomy, dropdown, terms"
} |
Slick Social Share Buttons plug-ins with Responsive theme - number of tweets link problem
I've just installed latest version of Slick Social Share Buttons on top of Responsive theme.
In the settings page in Twitter Username I provided my twitter username. The number of the times the link was hared shows fine in the widget, but if I click on the link, I'm taken to URL ` which it not found.
I assume the proper url it needs to take me to should be something like `
Am I missing something or its something wrong with plugins ?
!enter image description here
**Clicking on number 1 takes me to page :**
!enter image description here
!enter image description here | This should work just fine, because the functionality to share a website on Twitter should include the URL that you want your users to share. Keep in mind that the realtime Twitter-Searchfunction just shows recent results, not all of them, so the Link will never list all Tweets about your site.
The additional information section looks to me as if there was a possibility to show a 'Follow me on Twitter' button, which should include your username. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, social sharing"
} |
How to fix missing function in wp-cron?
One of my sites consistently fails to publish scheduled posts. I've tried disabling plugins, using Twenty Twelve, etc. with no luck.
I installed the Core Control plugin and noticed that there is no function associated with the publish_future_post hook. On my other sites, there is a hooked function check_and_publish_future_post() but it's missing on this particular site.
My questions are (1) how the heck did this happen and (2) how do I fix it? I've tried a clean install of Wordpress (other than wp-content) with no change. I've reached the limit of what I'm comfortable doing without some guidance, so I'm hoping someone here can help. | You can also disable the auto wp-cron from loading and setup a manual cron job on your server.
Add the following line to your Wp-config.php `define('DISABLE_WP_CRON', true);`
and then on your server/control panel create a cron job to run the following:
`wget > /dev/null 2>&1`
I run mine every 5 minutes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp cron, scheduled posts"
} |
How to filter categories of a post
Is there any way to filter the categories of a post? I am using `wp_get_post_categories( $post -> ID );` i want to filter this listing i.e. `if(post_name or post_id == "some id or some name") {it should not be displayed}` | have you tried something like,
$post_categories = wp_get_post_categories( $post -> ID );
foreach($post_categories as $c){
$cat = get_category( $c );
if ( $cat->slug != "cat" ) {
echo "$cat->name";
};
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, categories"
} |
How to align bold,italic and underline in wp-admin?
When Im in wp-admin and editing a page and whant to make underline, bold and italic it dont appear on the site. I understand therese something i have to define in the css or thru wp-admin ?
NOTE: I want the user to easly edit and i know how to do it thru css. But what I want is to edit thru the edit-page. | If it is editor mode specific, then make a CSS file named: `editor-style.css` and then add the following code into `functions.php` within PHP tags:
// CUSTOM EDITOR STYLES
// This theme styles the visual editor with editor-style.css to match the theme style.
add_editor_style();
Now put some CSS code to match the site's CSS into the editor. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, wp admin, css"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.