INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Is it possible to enqueue a raw CSS string directly from within a template file?
I was wondering if it's possible to enqueue raw CSS as a string directly from within a template file?
I'm writing a custom template for a page and need to add some style rules for it. What I want to do is write the styles out as a string var in PHP then use the enqueue_style function to load these styles, rather than me having to add them in to 'style.css' or some other external style-sheet.
I assumed that so long as I enqueue my styles before calling the 'get_header' function, and if I hook in to the 'wp_head' or 'wp_enqueue_styles' actions, that this would work but it doesn't appear to and I'm not sure if 'wp_enqueue_style' can take a raw CSS string.
Anyone got any advice please?
Kind regards,
Chris | Yes and no.
You _can_ load a raw CSS string into the header programatically, but you can't use `wp_enqueue_style()` to enqueue it. That function specifically loads _files_ into the header in `<link>` tags.
But what you can do is something like this:
function print_inline_script() {
?>
<style type="text/css">
/* ... styles go here ... */
</style>
<?php
}
add_action( 'wp_head', 'print_inline_script' ); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "css, page template, wp enqueue style"
} |
After moving my site from a dev subdomain, to root, all my custom meta data is gone
I just movde my site from a dev subdomain, to the root. I have extensive amounts of data saved in custom meta fields which I created with the WpAlchemy class. All of this data is not appearing in the site (back or front end), although it appears to be in the database.
This happened right after attempting to use the search replace plugin to change any lingering urls. This attempt ended in `Fatal error: Out of memory`. I noticed everything was gone, so I swapped out the db for my backup (after doing a manual search-replace for my subdomain). This produced the same result.
I think I've read somewhere that data serialization (am I getting this right?) can mess up this kind of thing. Is that whats happening to me here?
What steps should I take to get the site up and running ASAP. Currently it is live, and terribly broken :-( | Been there done that. Try this: < Its a search and replace tool that you put in your WordPress root and just run it from mydomain.dev/searchreplacedb2.php
It fixes the serialization problem when you want to change the url:s to the live one. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom field, database, migration, wpalchemy"
} |
Multilanguage Post Titles not Translating with List Category Posts Plugin
For the most part the plugin List Category Posts works great.
I just have one problem with it: when I try to show the title and excerpt of a post it shows all translations at the same time, rather than just the translation relative to the selected languages.
I'm using qTranslate for the languages. I'm not sure how to fix that. | I found a hint towards the solution exactly where you advised me. I think the solution was a bit outdated, but with a bit of digging, I made the following change:
in file `include/CartListDisplayer.php`, in `function get_post_title()` I added the following code in first line before anything else:
if ( function_exists( 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage' ) )
{
$single->post_title = esc_html(
qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage( $single->post_title )
);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin list category post"
} |
How to Remove the "Restore" Link in Quick Edit?
I want to know is there any hook to remove the **`Restore`** link in the edit page - trash page?
`/wp-admin/edit.php?post_status=trash`
I know I can hide it with a css/jquery trick, but I prefer to use a hook for this.
!enter image description here | This will do:
add_filter('post_row_actions', 'wpse_56560_remove_untrash', 10, 2);
add_filter('page_row_actions', 'wpse_56560_remove_untrash', 10, 2);
function wpse_56560_remove_untrash( $actions, $post )
{
if( !isset( $actions['untrash'] ) )
return $actions;
// If NOT administrator, remove Untrash
if( !current_user_can('administrator') )
unset( $actions['untrash'] );
return $actions;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "admin, hooks"
} |
How to run WP_Query to retrieve attachments to posts only from a particular category?
I have a WP blog with a few pages and posts and several categories. I want to write a loop to retrieve images attached to the posts (not the pages) and only those from a specific category and it's children. The category id is 60.
This is the WP_Query call:
$my_query = new WP_Query( array(
'post_type' => 'attachment',
'cat' => '60',
'post_mime_type' =>'image',
'posts_per_page' => $batch_size,
'nopaging' => false,
'post_status' => 'all',
'post_parent' => null,
'meta_key' => 'my_hash',
'orderby' => 'meta_value'
) );
But I get nothing!
What am I doing wrong? | You'll need to first grab the posts, then grab the attachments that are children of said posts.
$my_query = new WP_Query( array(
'meta_key' => 'my_hash',
'nopaging' => true,
'orderby' => 'meta_value',
'fields' => 'ids',
'cat' => '60',
));
if ( $post_ids = $my_query->get_posts() ) {
$post_ids = implode( ',', $post_ids );
$atts_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_parent IN($post_ids) AND post_type = 'attachment'" );
$my_query->query( array(
'posts_per_page' => $batch_size,
'post_mime_type' =>'image',
'post_status' => 'all',
'post_type' => 'attachment',
'post__in' => $atts_ids,
));
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "categories, wp query, attachments"
} |
Remove the category/taxonomy description field?
How can I remove the category/taxonomy description field? The one which shows up on the edit category/taxonomy page. | When no hook is available, you can always count on the old jQuery trickery...
add_action( 'admin_footer-edit-tags.php', 'wpse_56569_remove_cat_tag_description' );
function wpse_56569_remove_cat_tag_description(){
global $current_screen;
switch ( $current_screen->id )
{
case 'edit-category':
// WE ARE AT /wp-admin/edit-tags.php?taxonomy=category
// OR AT /wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=1&post_type=post
break;
case 'edit-post_tag':
// WE ARE AT /wp-admin/edit-tags.php?taxonomy=post_tag
// OR AT /wp-admin/edit-tags.php?action=edit&taxonomy=post_tag&tag_ID=3&post_type=post
break;
}
?>
<script type="text/javascript">
jQuery(document).ready( function($) {
$('#tag-description').parent().remove();
});
</script>
<?php
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 9,
"tags": "taxonomy, description, categories"
} |
How to Override a Pluggable Function
How can I override a function in pluggable.php?
I have tried making my own plugin -- got the fatal error on function already defined.
I tried functions.php in my theme -- got the white screen.
Is it possible to override a pluggable.php function without touching the source code file itself?
Thanks.
**Here is the function I wish to override (located in ../wp-includes/pluggable.php):**
if ( !function_exists('wp_new_user_notification') ) :
/**
* Notify the blog admin of a new user, normally via email.
*
* @since 2.0
*
* @param int $user_id User ID
* @param string $plaintext_pass Optional. The user's plaintext password
*/
function wp_new_user_notification($user_id, $plaintext_pass = '') {
...
} | Wrap it in a `function_exists` check:
if( ! function_exists('some_pluggable_function') ) {
function some_pluggable_function()
}
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "plugins"
} |
if get_post_meta is empty do something
I need opposite of this:
<?php if ( get_post_meta($post->ID, 'price_list_category1', true) ) : ?>style="display:none;"<?php endif; ?>
In other words I want `style="display:none;"` only when meta data doesn't exist.
I thought it would be straightforward like `if ( get_post_meta($post->ID, 'price_list_category1', true` but this true/false turns out to be a completely different stuff.
any ideas?
Thank you. | ~~You could use the`empty` function inside your `if` as such :~~
<?php if( empty( get_post_meta( $post->ID, 'price_list_category1', true ) ) ) : ?>style="display:none;"<?php endif; ?>
The above returns an error, you should assign the return value to a variable. See my edit below.
**Warning**
`empty` might not be the best option depending on the values you store in the meta. Values like `false`, `0` etc... will be considered empty.
Check the PHP manual for the full list of values that are considered empty.
**Edit**
You can try assigning the meta to a variable, and using that in the `if` statement.
<?php
$price_list = get_post_meta( $post->ID, 'price_list_category1', true );
?>
And then...
if( empty( $price_list) ) : ?>style="display:none"<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 5,
"tags": "post meta"
} |
How to remove parent section from attachment URL?
I have buddypress installed. All URL goes under BP's URL structure. If an attachment belongs to a document in a group, the URL is:
I would like to learn how to change the attachment URL to:
Thanks! | The attachment URL is created in `wp-includes/link-template.php` in function `get_attachment_link()`. And there is a filter for you, passing the WordPress URL and the post id for the attachment. You can hook into that filter and return the URL you need:
add_filter( 'attachment_link', 'wpse_56619_unprettify_attachment_url', 10, 2 );
function wpse_56619_unprettify_attachment_url( $link, $id )
{
return home_url( "/?attachment_id=$id" );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "url rewriting, attachments, buddypress"
} |
Geolocate Custom Post Type on Save
I was wondering what hook i would use to geo-locate a custom post type when it is saved?
I have a Custom post type of Restaurant and I want to geolocate the address using googles api and then save it into another field(s) | On post save the 'save_post' action is run. You could hook your function that geolocates to that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, google maps, geo data, plugin types"
} |
Error establishing a database connection when migrating site to localhost
I'm wanting to make a version of my blog on my home computer that I can work on offline. I set up LAMP on my computer (running Ubuntu) and copied all of my files from my server (000 Webhost) with FileZilla. But when I try to access my site on my localhost, I get "Error establishing a database connection." I think I've figured out that it has something to do with MySQL, but I'm really new to all this and could be way off. Any help would be greatly appreciated. Thanks in advance. | Did you change your database settings in `wp_config.php` and copy your database to your local machine? You'll also need to use a text editor to search a dump of your database for any URLs pointing to the live site before importing it locally if you haven't done so already. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database"
} |
Serving Cookies From A Different Domain or Sub-Domain
The WordPress Codex clearly states that if your website is served from `example.com`, for the sake of performance, you can have the cookies served from `www.example.com` by adding this to your wp-config.php:
define('COOKIE_DOMAIN', 'www.example.com');
**Problem:**
* The cookies are still being served from `example.com` and not `www.example.com`. What's wrong? or does this no longer work?
_**PS:** Edited to be precise._ | Looks like I mis-interpreted what's said in the codex. So, here's the thing...
This is what WordPress does by default: `define('COOKIE_DOMAIN', '.example.com');` — which means, cookies are sent with all the sub-domains, including `example.com` itself, even if your WordPress website itself is hosted on `www.example.com`.
Basically the point is, when your WordPress site is served from `www.example.com`, you can also have the cookies sent only with `www.example.com` and not other sub-domains, by adding this in your wp-config.php:
define('COOKIE_DOMAIN', 'www.example.com');
So, at most, what the aforementioned code does is restrict the cookies to the sub-domain that serves your WP site.
**NOTE:** And just in case it's not clear -- it's pointless to use `define('COOKIE_DOMAIN', 'www.example.com');` when your site itself is served from `example.com` or some other sub-domain, and not 'www.example.com'. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "cookies"
} |
Plugin to redirect all 404 pages to a specific page
I want to redirect all 404 pages to a specific page (not the homepage).
Is there any plugin that does that? | Just create a 404.php template file in the themes folder. All 404 redirects should be using this template file from then onwards. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
images in wordpress themes
I am developin a theme in php using wordpress.I want to display images on the website . so my question is what will be the best practise
1)store the image itself in a table using an "image" or "binary data" data type of the database server.
or
2)store the images as a file in the file system and create a record in a table with the exact path to that image. ..trying to bother the database as little as possible... . | Its never a good idea to store binary data in your database, take a look at this post: < and this post: <
In my opinion, its far faster to use the file system and here's why:
The image URL can be stored in a custom field by wordpress - this is very simple to do. The same representation of that image stored as binary is far larger than the image URL, therefore somewhat slower to fetch. You would also have to specifically write the code to do this. Its not native to wordpress. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, images"
} |
In wordpress how to sent different email separetly when i click on different email ids
I am using contact form 7 as a plugin in wordpress but i dont know how to sent different email separetly when i click on different email ids | The documentation for Contact 7 is pretty clear about how to do this - you just need to create a separate mail template for each form and edit the basic header fields
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, email, plugin contact form 7"
} |
Echo used hierarchical taxonomies parent name
I want to echo my hierarchical taxonomies parents which I used in my posts.
I've see answers about that, but no one didn't help me.
To get all taxonomies, currently I use
<?php the_terms( $post->ID, 'mytaxname', '', ' / ', ' ' ); ?>`
How to get only parents of used tax's? | Try this:
<?php
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$parent = get_term($term->parent, get_query_var('taxonomy') );
echo $parent->name;
?>
You have to get the current term slug and then use get_term by the slug and then echo the name. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "taxonomy, terms"
} |
How to make registration form ajax?
I have a registration form and I would like to make it ajax, is there such plugin or how can I adjust the standard wordpress registration page to be ajax without reloading page. Thanks in advance. | **Login With Ajax** is a very actively developed plugin that enables AJAX Login / Registration without refreshing your screen. It has a number of other features as well, take a look. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "ajax, user registration"
} |
Wordpress redirect to landing page if not logged in
I'm using the following code in my functions.php file to redirect users who are not logged in to a particular landing page
<?php
if(!is_user_logged_in()) {
wp_redirect( ' 301 ); exit;
}
The problem is I cannot access my wp-login or wp-admin anymore. Every url redirects to landingpage. Is there a way I can exclude certain urls from redirecting? | something like:
if (
!in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'))
&& !is_admin()
&& !is_user_logged_in()
) {
wp_redirect(' 301);
exit;
}
should do it.
see < & Check if wp-login is current page | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "php"
} |
Do I use cookies?
I have made website in wordpress, and now client wants to know do this website use cookies?
I dont know too much about it becouse i never use it, but i need to be sure. If I make websites i use session, and I quess the same is in wordpress, but as I said, dont know too much about it and client need this information.
I also use PIWIK stats.
Is there a way to check it? I can give you list of plugins I used. | Yes, any WordPress site does uses cookies. By default, WordPress uses cookies to verify who the user is, i.e. if the user is logged-in (registered user) or is a commenter on the site. (More Info.)
Plugins and theme's may set cookies. For example, Cookies for Comments plugin uses cookies to prevent comment spam. Cookies have their own purpose.
Check your browser preferences (or in the dialog box when deleting history), you should see an option similar to "Manage Cookies", which shows a list of cookies sent by your website.
**BTW** , WordPress does not use sessions. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "cookies"
} |
Make WordPress process admin group comments using $allowedtags
WP uses `$allowedtags` to limit the set of allowable tags for comments.However, comments from administrators are unfiltered.
What's the easiest way to ensure admin comments are also constrained to the tags contained in `$allowedtags`? | `kses_init` is hooked onto the `init` hook with default priority, and (after first removing any of the kses filters) adds filters which strip out tags (`wp_filter_post_kses` for posts and `wp_filter_kses` for comments) if the user does not have the capability 'unfiltered_html'.
Since the capability determines whether or not the user can post 'unfiltered_html' comments _and_ posts - you probably don't want to just remove that capability.
Instead, hook onto `init`, _after_ `kses_init`, say with priority 20, and re-add the filters which strip out tags not in the `$allowedtags` whitelist:
add_action('init','wpse56687_filter_everyones_comments',20);
function wpse56687_filter_everyones_comments(){
add_filter( 'pre_comment_content', 'wp_filter_kses' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments, wp kses, allowedtags"
} |
Accept or deny cookies - how to?
As far as cookies privacy policy has been change, i need to make a script which allow to accept (or not) cookies by user for this domain (website) only. Is there a way to do this for one website only.
Second thing is this popup window should be displayed only if user came from different domain (so each page have to check it - template/header).
How can i do this? | If your question is regarding the new EU cookie policy, you only have to worry about third party tracking cookies that track between sites, WordPress cookies don't fall within that category. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "cookies"
} |
Faking the "onSave" event
While a specific use-case, I believe this may benefit others.
I am using TurboCSV to mass-import a number of posts into WordPress (which it is doing wonderfully so far). Within that import, I am specifying custom fields to be used in conjunction with Advanced Custom Fields to store/output the data. The post_meta table is being created correctly, but the part that is not working as expected is generating ACF's hidden fields (which work with field relationships). When the import is first done, those database tables are not created until you manually go into each post and re-save them. I was wondering if there is a way to "fake" the onSave event for WordPress for a number of posts. ACF also passes along post information (stored on the post edit screen) to this save function - which makes it a bit trickier - but I'd be interested if anyone has any thoughts. Thanks! | Have you seen wpshell? It's a command line tool for wordpress. Basically, it's a Wordpress environment that lets you run arbitrary php - so you could set up a `WP_Query` that pulls all posts, loop through them, and fire that command on each one.
Sort of what I had in mind, untested. Using `wp_update_post()` as it contains the `save_post` hook, and is the equivalent of hitting 'update' on the post edit screen:
$args = array('posts_per_page' => -1, 'post_type' => 'any')
$query = new Wp_query($args)
while ( $query->have_posts() ) : $query->the_post();
$post->wp_update_post();
echo $post->ID . '<br />';
endwhile;
echo 'Done! Everything saved!'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "import, save post, advanced custom fields"
} |
How do I register a stylesheet inside a WordPress widget?
I'm developing a WordPress widget following Dave Clements tutorial. It works well. Now I want to add some styles to it. I want the styles to be in an extra css file which will be loaded during runtime. I'm calling this function
function myprefix_add_my_stylesheet() {
wp_register_style( 'myprefix-style', plugins_url('mystyle.css', __FILE__) );
wp_enqueue_style( 'myprefix-style' );
}
right before (see Dave's tutorial) "// Widget output //" using the following statement.
add_action( 'wp_enqueue_scripts', 'myprefix_add_my_stylesheet' );
But nothing seems to happen. What am I doing wrong? | `wp_enqueue_scripts` is called way before WordPress processes the widget content, so just as in this post, you've missed the boat :).
Instead, just call `wp_enqueue_style` directly:
function widget($args, $instance) {
wp_enqueue_style( 'myprefix-style', plugins_url('mystyle.css', __FILE__) );
//Widget content
}
(no need to register if you're just going to enqueue it straight after). Same works for `wp_enqueue_script`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugins, plugin development, widgets, css"
} |
Redirect all www.xyz.com to www.xyz.com/wordpress?
I have my website working from www.xyz.com/wordpress, but customers should not need to type it all. If they just type www.xyz.com it should take them to www.xyz.com/wordpress. | To redirect ` to ` add these rules to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?xyz.com$
RewriteRule ^(/)?$ wordpress [L]
That answers the first part of your question. The rest of it is totally vague to me. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "deployment"
} |
Saving custom fields to a custom taxonomy
I am trying to create a custom field for a custom taxonomy. update_post_meta works great with posts. Taxonomies are not posts so this won't work.
<?php update_post_meta($post_id, $meta_key, $meta_value, $prev_value); ?>
How would I save a custom field within a custom taxonomy? Other solutions include the options_table (bad!) or creating a custom table (cumbersome). Is there another, canned solution or function to help with this? | update_metadata()
great post on Adding Custom Fields to Taxonomy.
The solution outlined does require creating an additional database table but it does the job perfectly. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "posts, custom taxonomy, post meta, advanced custom fields"
} |
How to sort posts in a custom post type by title in ascending order by default?
So I am using a custom post type to create a listing of businesses. Each post made, contains information about each business. The title of each post is the name of the business.
When I go to the menu created by the custom post type, I receive a standard listing of posts. (or in this particular case, a listing of business names). The posts show in a random order (or possibly being sorted by date on default?)
How can I allow for my posts to be listed in alphabetical ascending order by default? | You should use `pre_get_posts`:
add_action('pre_get_posts','wpse56753_businesses_default_order');
function wpse56753_businesses_default_order( $query ){
if( 'business' == $query->get('post_type') ){
if( $query->get('orderby') == '' )
$query->set('orderby','title');
if( $query->get('order') == '' )
$query->set('order','ASC');
}
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "custom post types, posts, customization, sort, wp list table"
} |
plugin to organize data
I am currently converting this page into a wordpress site. Now as you can see on the page I linked to, I need some sort of way to organize the data on the site. I have already looked for a plugin for the job but I can´t find the right thing. can someone suggest a plugin that could do the job?
things that the plugin should do:
* let the admin add more data into pre defined fields through backend
* add the new data into the appropriate position on the site (sort alphabetic by name)
* alpha index at the top to quickly jump to desired letter in alphabet | I found a good plugin afterall:
post index
this plugin makes it easy to create a list with an alphaindex from articels from a specific category. just make a new page, put the shortcode from the plugin which specifies the category on it and its done. all article from that category are now added to the list. the article names are sorted alphabetically and link to the actual post. just what I neede, maybe somebody else is looking for something like this as well. you can see it here in action (temporarily) link | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Custom role can't create permalink
My user post a new custom type "artprim_item" and it doesn't work unless I remove permalinks. The item is created, but the permalink links to "item not found".
More importantly, if I open the item with my admin account and update it, the permalink works at last.
Since I only want him to see "artprim_item" and no "page, posts, links...)" , this user has a role that I created with limited capacities:
* delete_artprim_item
* edit_artprim_item
* edit_artprim_items
* edit_others_artprim_items
* publish_artprim_items
* read_artprim_item
* read_private_artprim_items
* upload_files
* edit_files
* read
Is there a capacities to create permalinks? | Found that it works if I add the `edit_posts` capacity.
But `Posts` is now visible in Admin :(
At the same time, it also fixed a problem I had with Media upload: the user could never edit right after the upload. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, permalinks, user roles"
} |
Get main parent categories for a product
Can someone please help me, I'm looking for a way to find the main parent product category of a WooCommerce product? Say, the product is marked under Gadgets, but the main parent of them all is Electronics.
I want this per post, as I want to add a class to each post signifying its main parent `product_cat`.
Please remember, product categories are custom taxonomy, and cannot be retrieved using `get_category_parents()`. They are listed as terms.
Thanks in advance.
// edit:
This is the code I have already, I'm calling this on each post and my posts are rendered similar to an archive page.
function all_cat_classes($post) {
$cats = "";
$terms = get_the_terms($post->ID, "product_cat");
$count = 0;
$count = count($terms);
$key = 0;
foreach ($terms as $cat) {
$key++;
}
return $cats;
} | I wrote my own function to go all the way up the "chain". My recursive might not be the best implementation you've seen, but it works.
function get_parent_terms($term) {
if ($term->parent > 0) {
$term = get_term_by("id", $term->parent, "product_cat");
if ($term->parent > 0) {
get_parent_terms($term);
} else return $term;
}
else return $term;
}
# Will return all categories of a product, including parent categories
function all_cat_classes($post) {
$cats = "";
$terms = get_the_terms($post->ID, "product_cat");
$key = 0;
// foreach product_cat get main top product_cat
foreach ($terms as $cat) {
$cat = get_parent_terms($cat);
$cats .= (strpos($cats, $cat->slug) === false ? $cat->slug." " : "");
$key++;
}
return $cats;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom taxonomy, terms, plugins"
} |
Date based CSS/theme
Is it possible to set a CSS stylesheet or a theme for articles that were published before X date?
The reason I ask is that we've just redesigned our website and some pages have images that are wider than the page size now. | I php you can create an anchor class based on the desired date. I haven't tested it, but it should be something like this:
// your relevant html parent element
<div class="<?php echo getOlderPostsClassName( '5/5/2012',the_time() ); ?>">
function getOlderPostsClassName($untilDate, $wordpressPostDate)
{
$start = strtotime($untilDate);
$end = strtotime($wordpressPostDate);
if ($start-$end > 0)
{
return 'My_css_class_for_older_posts';
}
else
{
return '';
}
}
Then in your Css you can target differently any descendant element:
.My_css_class_for_older_posts h2{
color:red;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, css, date"
} |
Is there a way to serve different resolution images to different devices?
I am making a mobile site, and I want to serve higher resolution images to devices with high pixel density, and normal image to the rest, is there a Wordpress functionality or plugin to help me do that?
I'm not looking for non-wordpress libraries/plugins. | Here are some plugins that may be just what you're looking for:
<
<
.. also take a look at this post: <
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, themes, images"
} |
Wordpress Site footer on Firefox displays a error
On Firefox I get the following below the footer
`Performance Optimization WordPress Plugins by W3 EDGE
Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'Array' was given in /somedirectories/wordpress/wp-includes/plugin.php on line 405`
On Chrome it works fine and the last line on the footer is
`Performance Optimization WordPress Plugins by W3 EDGE` | This is not an error, it is a warning. You can make this go away by:
* Fixing the warning
* Write errors to the error log instead of the screen ( best practice )
To fix the error, I recommend looking at what's hooking into wp_footer etc, or using a PHP debugger | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "footer"
} |
How to save media-form on custom tab
On my custom tab, I copied media-form from media_upload_gallery_form, only changed form id and action-url to reflect my tab's name. The form displayed as expected, but after click "Save All Changes", the post data is not saved. Please note unlike custom fields that we add filter to "attachment_field_save", this time it is the entire media-form. It can be saved on either Gallery tab or Library tab, so I guess there has to be a way to be saved on my custom tab? | Just figured out this one-- in the function that load the iframe, add this:
if ( !empty($_POST) ) {
$return = media_upload_form_handler();
if ( is_string($return) )
return $return;
if ( is_array($return) )
$errors = $return;
}
Then, all the form data get saved as normal. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "attachments, gallery, media library"
} |
WordPress in Drupal
I got a Drupal site, and I must install WordPress in it.
If I install WordPress to "www.mysdrupalsite/wordpress/", will it work as a standard WordPress installation ?
THANKS ! | If your are trying to make them run independent from each other, your suggestion should work fine. (Assuming you mean "www.mysdrupalsite.com/wordpress/".) Just make sure you create a separate database for this new wordpress installation. If you have only one database and it is already in use, you can install WordPress in it - just make sure to have a distinctive prefix for your tables, to avoid over-writing any existing database table.
Combining the two in one (for example users can use both, only singing up once) will be much tougher. If your looking for this, please let me know and I can explain it for you.
* * *
More/all indept information on how to install wordpress can be found here. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "cms"
} |
Certain BuddyPress Member Profile Data Getting Hyperlinked
Very odd behavior in BuddyPress. When we enter various pieces of information in the About Me textbox on the members profile data in BP, some content is getting hyperlinked as `../members/?s=my content`
Has anyone seen that? How can I correct it or shut off the hyper-linking?
Thanks. | `// 2012-07-11 -- turns off hyperlinking of content on Members Profile remove_filter( 'bp_get_the_profile_field_value', 'xprofile_filter_link_profile_data', 9, 2 );` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "buddypress"
} |
WP E-Commerce creating categories programmaticaly
I was searching WP Ecommerce documentation, trying to find what function to use to add category to WPEC, but no luck. Is there some function or piece of code that can do this? | You can use `wp_insert_term` to add terms to the `wpsc_product_category` taxonomy:
<?php
$args = array(
'description'=> 'term description.',
'slug' => 'my-term'
);
wp_insert_term( 'My term', 'wpsc_product_category', $args );
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, e commerce, plugin wp e commerce"
} |
Preview Changes button missing on custom post type page since updating to 3.4
Any idea why when I'm on post.php of my custom post type page I no longer see the Preview Changes button?
I have checked on an old installation and it shows on WordPress version 3.3 but not 3.4.
The custom post page has this HTML:
!enter image description here
A normal post page has:
!enter image description here
Why is my custom post page missing the div preview-action in the latest version of WordPress? | I run through exact same issue. Later I come to know that custom post type I created was not public and hence it does not have 'Preview Changes' button visible.
Prior version of Wordpress was displaying that button but it seems they have fixed it now.
To fix it, make sure you set ' **public** ' to ' **true** ' in array of arguments you are passing to ' **register_post_type function** '.
Hope it will help!
Neerav | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, previews"
} |
Plugin List Category: post custom field doesn’t show anything
I'm using the Plugin List Category to show a list of posts and I use it with the parameters:
[catlist name=talleres thumbnail=yes thumbnail_size=52,52 excerpt=yes customfield_display=featured]
But it doesn't show anything for the custom fields. I tried with different parameters, still nothing. Does anyone have an idea, do I have the syntax wrong? | still don't know what exactly fixed it. but now it's all right. i have also found another way to show custom fields: if you want to show a specific field in a specific place, in the CartListDisplayer.php, add to the function lcp_build_post anywhere you like: $lcp_display_output .= get_post_meta($single->ID, 'featured', true);
where featured is the name of yuor custom field. Hope it can help someone. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin list category post"
} |
associate posts to a page
I created a theme, and I created a page for the theme, and now I want to associate posts to the page. I read this article:
<
Look under the section "Examples of Pages and Templates", there is this code:
<div id="content" class="widecolumn">
<?php if (have_posts()) : while (have_posts()) : the_post();?>
<div class="post">
<h2 id="post-<?php the_ID(); ?>"><?php the_title();?></h2>
<div class="entrytext">
<?php the_content('<p class="serif">Read the rest of this page »</p>'); ?>
</div>
</div>
<?php endwhile; endif; ?>
It seems to be pulling some posts associated with a page. How can I create posts for a page? And if not possible, what are they doing or what kind of altenrative is available to me, other than hardcoding html into the page? | You can use `wp_query` with different arguments to list the posts that you want to appear on that specific page (i.e. all the post that are assigned to the X category or all the post that belong to Y author a.s.o). You can find on the Wordpress Codex a detailed presentation and examples on how to use wp_query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, pages"
} |
How to format the first line of a post differently?
I'd like to have the first paragraph/sentence of my posts in their single.php page styled differently - say... bold.
How do I go about doing that in the most efficient way? | In the end, this is the function that worked for me:
add_filter('the_content', 'first_line_bold');
function first_line_bold($content)
{
if (!is_page()) {
$pattern = "/<p.*?>([^`]*?)<\/p>/";
$match = "<span style=\"font-weight:bold;font-size:16px;\">$1</span>";
$content = preg_replace($pattern, $match, $content, 1);
return $content;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, single, css"
} |
Remove specific page/post from feed
I'm working on a website with lots of tutorials/pages.
I have made a separate rss feed for the pages - works fine. But then I had to create a sitemap (a page), and it shows up in my "pages" rss feed!
**My Question:** How can I remove a specific post/page from a feed? | The quick and dirty way is set the published date a year or so in the past, past the oldest posts in the feed. There's also a nice plugin for this - Stealth Publish \- where you set a flag in a custom field to exclude it from feeds and the home page feed. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "pages, rss, feed, customization"
} |
Tags and Taxonomy links not working for Custom Post Types
In my theme, I registered a taxonomy by the name of `tax_groups` for a custom post type named `custom_items`. So the following URL was returning the lastest `custom_items` <
The Search widget was also working perfectly fine but not Tag and Taxonomy links like these:
| I had to modify queries before they run. So the best practice was to add the following code to function.php:
if (!function_exists('my_theme_filter')) {
function my_theme_filter( $query ){
if ( $query->is_main_query() )
if ( $query->get( 'tag' ) OR is_search() )
$query->set( 'post_type', array( 'artprim_item' ) );
//echo '<pre>'; print_r($query); echo '</pre>';
return $query;
}}
add_filter( 'pre_get_posts', 'my_theme_filter' );
* `if ( is_search() )` was necessary for taxonomy, this is what made this URL works :
<
It's surprising and made me lost a lot of time since the search by itself was already working just fine
* `if ( $query->get( 'tag' ) )` obviously was necessary for
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, tags, urls"
} |
How to create a customized logout URL in BuddyPress
Does anyone know how to override the BuddyPress logout URL with a custom one? | That’s the same as the regular WordPress logout URL. So you can use the same filter: `'logout_url'`.
Sample code, not tested:
add_filter( 'logout_url', 'wpse_56866_logout_url' );
function wpse_56866_logout_url()
{
// set your URL here
return '
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "buddypress"
} |
How to only hook on Single.php after content?
I am currently hooking on `the_content()` but that goes through the Wordpress loop too. How can I only hook on the Single.php page?
Also, is there a way to only look on the first X posts in the Wordpress loop?
By the way, I am creating a plugin | This will handle appending the content to single posts:
function yourprefix_add_to_content( $content ) {
if( is_single() ) {
$content .= 'Your new content here';
}
return $content;
}
add_filter( 'the_content', 'yourprefix_add_to_content' ); | stackexchange-wordpress | {
"answer_score": 20,
"question_score": 6,
"tags": "plugins, filters, hooks, actions"
} |
Can someone (Support of my themeprovider) get access to my server If I send them my admin login?
I have bought a WP theme from a huge provider (themeforest). But it has a lot of bugs. The support asked me to send my WP Admin Login/Password. What risk does this have?
I know the supportstaff will have full access to the WP installation, with the WP admin credentials. this is ok for me.
But what about the server this instances is running on? Are there any changes that they would theoretically get access to the server? This is a no-no. As the sever hosts a lot of confidential stuff.
My Guess: Most likely yes, they could get access? (As far as I can tell they could input some php code in the wp-code-editor that opens up a shell or reads some files in the system?) Or am I wrong?
thanks! | If you give the provider full admin, they can technically do anything to your server that PHP would be able to do (by using the editor part of a given theme to add whatever commands they like). PHP is capable of running command line scripts, just to name one scary permission they would inherit.
Depending on what user (on the server, not in your WordPress install) you have running page scripts, that could be complete control or just control of some web portions of your server. Either way, it would not be insignificant.
I can't think of anything beyond the theme editor that would put your server in danger, but if they are providing the theme, I would think they would need access to that in order to do much so I don't know that there's a good option for you to keep your server safe and give them what they're asking. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "security"
} |
Loading scripts on specific page
I tend to place my wp_enqueue_scripts hooks on my functions.php but this ends up piling up scripts across my site.
Which makes more sense?
# 1:
function load_slider(){
global $post;
if($post->ID == 11746){ // Load slider on home page
wp_register_script('start-slidorion', get_bloginfo('stylesheet_directory') . '/js/slidorion/start.js', array('slidorion', 'jquery','easing') );
wp_enqueue_script('start-slidorion' );
}
}
add_action('wp_enqueue_scripts', 'load_slider');
# 2:
function load_slider(){
wp_register_script('start-slidorion', get_bloginfo('stylesheet_directory') . '/js/slidorion/start.js', array('slidorion', 'jquery','easing') );
wp_enqueue_script('start-slidorion' );
}
global $post;
if($post->ID == 11746){ // Load slider on home page
add_action('wp_enqueue_scripts', 'load_slider');
} | method two won't work because no page is loaded yet and $post isn't set when your if check runs.
with method one again $post is not yet set at that point, but this method will work if you use WordPress conditionals:
function load_slider(){
if( is_page(11746) ){ // Load slider on home page
wp_register_script('start-slidorion', get_bloginfo('stylesheet_directory') . '/js/slidorion/start.js', array('slidorion', 'jquery','easing') );
wp_enqueue_script('start-slidorion' );
}
}
add_action('wp_enqueue_scripts', 'load_slider');
**EDIT** another example using `has_term`:
function load_slider(){
global $post;
if( has_term( 'your category', 'category', $post ) ):
// enqueue your script
endif;
}
add_action('wp_enqueue_scripts', 'load_slider'); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "server load, performance"
} |
How to query posts from single post format on Genesis framework
How to query posts from single post format on Genesis framework? I want to just show posts from **gallery post** format only.
I tried this query:
<?php
$recent = new WP_Query(
"taxonomy=post-format&field=slug&terms=post_format-link&posts_per_page=5"
);
while($recent->have_posts()) :
$recent->the_post();
?>
But I didn’t get what I wanted. | The taxonomy should be `post_format` and term should be `post-format-link`. Also simple taxonomy queries are deprecated since 3.1 in favor of `tax_query`:
$args = array(
'posts_per_page' => 5,
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => 'post-format-link'
)
)
);
$recent = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "wp query, post formats"
} |
Get closest page ID from URL
Lets say on my WordPress website I navigate to:
> www.example.com/media-centre/news/17/an-example-news-post
In this case I am looking at a post in a CPT called `News`.
What I want to do is get the page ID thats closest to that URL. I know the closest page ID can be found at:
> www.example.com/media-centre/news/
So how do I loop back over my URL to find the closest page and then how do I get the ID of that page? | Got there myself with the aid from Stephen Harris and some PHP help over at SO.
$page = get_closest_page();
// echo $page->ID;
function get_closest_page( $url = false )
{
global $wp;
if( ! $url )
$url = $wp->request;
$page = get_page_by_path( $url );
if( $page )
return $page;
$url = dirname( $url );
return get_closest_page( $url );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks, pages, urls, parse"
} |
Display an archives name
I want to display the current archives name, so for the url below I could do something like this
<h1><?php echo "answer" ?></h1>
which would output something like this
<h1>News</h1>
or better yet
<h1>News: supplierName</h1>
< | This is probably what you need:
<?php if (is_category()) { // Show only on Category archive pages ?>
<h1><?php echo single_cat_title('News: '); ?></h1>
<?php } elseif (is_tag()) { // Show only on Tag archive pages ?>
<h1><?php echo single_tag_title('News: '); ?></h1>
<?php } ?>
OR like this (as @StephenHarris pointed out):
<h1><?php
if ( is_category() || is_tag() ) {
single_term_title( 'News: ', false );
}
?></h1> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "archives"
} |
switch_to_blog() for parent theme
all. Just trying out switch_to_blog() as a way to have a child site get some news items from the parent site. Problem is, the parent site--first tables in database--doesn't have a number, i.e., tables are like www_posts--there's no number to put in the parentheses, 0 doesn't work, empty doesn't work.
How can I reference this original install? Also, is it no longer cool to use switch_to_blog()?
Thanks! | `switch_to_blog(1);` to switch to the root (primary) blog and pull post info.
`restore_current_blog();` to switch back. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "parent theme, switch to blog"
} |
Role Capabilities: Add New Ones?
I'm trying to create a private type of community ... and the current `Capabilities` are great, except for the fact that I don't want users of a certain `Role` being able to see anything that someone else has created (posts, pages, etc)
I'd love to be able to create some new `Capabilities` that would compliment my application, such as: `view_others_posts` ... I just don't want a user of a specific `Role` to see anything except what they've created.
Another REALLY important example would be the Media Library ... I do NOT want users of a certain `Role` being able to see ANYTHING besides what they themselves have added to the Media Library. Make sense? ...for Admins, they can see all, but I need some serious private limits for users that belong to new custom `Role`
Are there any ways of doing so? | User Role Editor plugin allows you to create custom roles easily, and if you wish, change any standard WordPress user role (except administrator) as well. This plugin is very well maintained.
But just in case you haven't, I would like to suggest that you first consider reading about the various pre-defined Roles in WordPress and their capabilities — WordPress Codex: Roles and Capabilities.
**EDIT:** Role Scoper allows you to assign restrictions and roles to specific pages, posts or categories. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom post types, user roles, capabilities"
} |
Trying to integrate wordpress query on other website - getting redirection to wp-install
i'm trying to replace news system on my website with posts from wordpress site. I have main site in (example) /var/www/site and working Wordpress blog on /var/www/site/blog
Tried to do that: < and neither wp-load nor wp-blog-header are working. I'm getting redirection to wp-install.
Strange thing is that php file put into main site main dir is working properly, but any try to require wp files inside main site structure (on init stage or on displaying page header) are failing.
What i am doing wrong? It's all happening on 3.4.1 WP version.
Cheers | Providing this will work if it's all on the same server.
This is the PHP I use at the top of non-wordpress site.
define('WP_USE_THEMES', false);
require('/home/sites/example.co.uk/www/wp/wp-load.php');
Obviously you just need to put your server path to the `wp-load.php` file.
Just write your news query and loop it should feed in the content to your non-wordpress site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "api"
} |
Memory question on Wordpress Multisite
Im currently using WP-Memory-Usage plugin on my wordpress multisite network to monitor my memory usage. The memory usage displays **39.1 MByte**. Does it mean **39.1 MByte** per blog? | No, this has to do with each page load and uses PHP's memory_get_usage() plugin.
Every page load will have a slightly different memory usage. Disabling plugins will decrease it, as the plugin doesn't have to load on that page.
This means that the usage will be different on every blog, and possibly on different pages in the blog. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "multisite, memory"
} |
How do I put up a splash page and have all WordPress links redirect to this page?
I would like to put up a splash page and have all site links (posts, pages, etc.) to redirect to this splash.
I know there are a number of ways to create a splash (i.e. page template in WordPress and set the front page as this template or even create an index.html file at the root of my WordPress install and rename the index.php file.)
What's the best way to accomplish this? Are there particular .htaccess commands that would be better option? | I'd usually use the the Maintenance Mode plugin which also includes some nice headers features and is easy to activate/deactive. Using the settings, if you want a custom splash page, you just put a 503.php file in the active theme and then set the plugin to use that as the redirect landing page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "redirect, htaccess"
} |
use wp_get_theme() to get theme author name
As of wordpress 3.4 we're supposed to use wp_get_theme to return theme data.
$theme = wp_get_theme();
//var_dump($theme);
echo $theme->Author;
despite the var_dump indicating the correct string, $theme->Author always returns a hyperlink with the author's name, but linked to the author's site. how can i get just the theme's author name? | Do not use just the header string, call `display()` instead and set the second parameter to `FALSE` to suppress markup.
// FALSE for no markup
$theme->display( 'Author', FALSE );
What you see in your `var_dump()` are _private_ properties. If you print `$theme->Author` the magic `__get()` method is called and this calls `display()` without the second parameter for `$markup`. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "wp get theme"
} |
How to Display a menu only if it has Posts in Custom Menu?
I created a custom taxonomy as category and display it by wp_nav_menu. The problem is, so far there are some terms in the custom taxonomy has no post attached to it, but it still show in the menu. So when people click on the menu link, they will got to a Nothing Found page.
How do I display the menu/term that only has post in it in wp_nav_menu? | Okay, I figure it out.
Instead of using wp_nav_menu, I use wp_list_categories which has more parameters that we can control. So to not display empty menu, I use:
<?php wp_list_categories(array('taxonomy' => 'custom_tax','hide_empty' => '1','title_li' => '')); ?>
the `hide_empty` do the magic here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom taxonomy, menus"
} |
disable jscrollpane in specfic div
I installed the library jscrollpane , and its working fine but i need to disable it in the #content that is in frontpage template //
jQuery.noConflict();
jQuery(document).ready(function($) { //tells WP to recognize the $ variable
//paste your jquery code here
$('#content').jScrollPane();
}); //end document ready functions
/* ]]> */
</script>
<
i just want to disable in frontpage but working on the rest of the theme Thanks | this should work-
$('#content').not('body.home #content').jScrollPane(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "child theme"
} |
Custom /page/2/ template (different from index.php)
I'm trying to create a custom page 2 template that's different from the main index.php. For example, the main index page would display the latest news + a lot of features like a magazine. When readers click to read on to page 2, 3, 4 etc of the news posts, they are taken to a more regular news page. Kinda like something on theverge.com (at the bottom, click "next page" and see what I mean).
Anyone have any ideas on how to do this? I know it's possible to create archive pages for categories and tags, but I'm not sure how to do it for the index.php.
Thanks! | I would use the `is_paged()` conditional inside `index.php` to load two separate templates containing your layouts. Something like this:
if ( is_paged() ):
get_template_part( 'content', 'first-page' );
else:
get_template_part( 'content', 'paged' );
endif;
Assuming you have two templates, `content-first-page.php` and `content-paged.php`.
**Edit:** If you just want a different template for part of your index page, try this:
if ( !is_paged() ):
get_template_part( 'content', 'middle' );
endif;
Put that wherever you want the extra template to load. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "pages, homepage"
} |
Archive custom template from search
I'm using this code for a dropdown of categories. On selection of the dropdown the desired category is displayed using the archive template. I cannot for the love of me get the template hierarchy to work.
<form>
<select name="tag-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value='#'>Select Taxonomy terms</option>
<?php $taxonomies = array('service-category');
$args = array('orderby'=>'name','hide_empty'=>true);
echo get_terms_dropdown($taxonomies, $args); ?>
</select>
</form>
I am using a custom post type called 'services' and a custom taxonomy 'service-category'. Is there a way to tell the search to use a different archive.php template? | From codex \- you should be able to use `taxonomy-service-category.php` template to display `service-category` posts. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, search, archive template"
} |
How to include custom code on a page that's set to act as homepage?
I have a page called 'home' which is set to be the front of my site, but I'd like it to show the most recent blog post or two at the bottom. I have some PHP that will do this from another site
<?php
query_posts('showposts=1');
while (have_posts()): the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_content('Read the rest of this entry »'); ?>
<p><a href="<?php echo $siteroot .'/blog/' ?>">Go to the Blog...</a></p>
<?php endwhile; ?>
But I'm not sure where to put it in order to make it so it only shows on this one particular page since `is_home()` returns false for the page. | Since you are saying it's a "Page", I believe you should try `is_page` instead of `is_home`:
<?php
if ( is_page( 'about' ) ) {
// Code to be shown on Page whose slug is "about"
}
?>
OR for the way your code is, this should do:
<?php if ( is_page( 'about' ) ) { ?>
<!-- Code to be shown on Page whose slug is "about" -->
<?php } ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, pages, homepage"
} |
WP Multisite development with Mamp Pro and wildcard subdomains, not really working for me
I´m trying to set up a local development environment for me to work on a Wordpress multisite that I´m building. I use Mamp Pro with default ports (Apache: 80, MySQL: 3306), and I also added a new host with the same domain name as the page will have when going live. So, now when I go to < I get to my development page, and database entries seem to use the same url as it should when going live as well. Enabling multisite from here was no problem, but I´m struggling to get Wildcard subdomains to work.
In the advanced tab under Host in Mamp Pro, I added: "ServerAlias *.mydomain.com", but that doesn't work for me. I´m able to add a new site from the Admin dashboard, but when trying to visit it I just get a 404.
Can anyone steer me in the right direction? I´m the 'design guy' so all this techinical jizz is really over my head, but I try...:) | Appart of the default ports and correctly configuring WPMS...
In the Advanced Tab:
!MAMP PRO
And manually add the subdomains in `/etc/hosts`1 file:
# BRASOFILO MULTISITE START
127.0.0.1 test1.brasofilo.dev
127.0.0.1 test2.brasofilo.dev
127.0.0.1 cloned.brasofilo.dev
# BRASOFILO MULTISITE STOP
1 _The folder`etc` is at the root of your HD and it's hidden. You can open the file using TextMate or with your FTP client (enabling `Show hidden files`). It can also be done with the Terminal, but I don't use it for that and you'll have to search How To..._ | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 7,
"tags": "multisite, subdomains, domain mapping, local installation, dns"
} |
FTP credentials on localhost
> **Possible Duplicate:**
> wordpress on localhost lamp doesn't let me install plugins
I just started working locally with Wordpress. Trying to update theme/plugins I get asked for my FTP credentials and I get really confused...what the heck is my FTP credentials when working locally? | **Set file permissions**
On Mac OS X (Leopard), the Apache HTTP Server runs under the user account, _www which belongs to the group _www. To allow WordPress to configure wp-config.php during installation, update files during upgrades, and update the .htaccess file for pretty permalinks, give the server write permission on the files.
One way to do this is to change the owner of the wordpress directory and its contents to _www. Keep the group as staff, a group to which your user account belongs and give write permissions to the group.
$ cd /<wherever>/Sites/<thesite>
$ sudo chown -R _www wordpress
$ sudo chmod -R g+w wordpress
This way, the WordPress directories have a permission level of 775 and files have a permission level of 664. No file nor directory is world-writeable.
You can read more about it on mamp forum: | stackexchange-wordpress | {
"answer_score": 55,
"question_score": 23,
"tags": "ftp, local installation"
} |
background/font size change and remember
I want to create font size and background change buttons, which i know how to do it. The problem is with remember it, so if user will go to a different page, background and font will stay the same. How can i do it?
I was thinking about saving this in cookies. What do you think about that?
Is anyone can write an example of saving valible in cookies in wordpress. | Here is how you can sett a cookie whit a variable: Now it saves for one day.
$settings = $mybackground;
setcookie('background',$settings,time() + (86400)); // 86400 = 1 day
Print it in the body like an img whit this:
echo $_COOKIE['background']; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "cookies"
} |
Get author's first name
I am probably being a little dumb here, but can anyone point me in the right direction.
I am trying simply display the authors first name as a link in my loop.
But the doesnt seem to be any options with the `get_author` tag.
This is what I got so far.
Posted by <a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" rel="author"><?php printf( __( '%s' ), get_the_author() ); ?></a>
Thanks Josh | You can use `get_the_author_meta( 'first_name' );` (see Codex for `get_the_author_meta`) | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "author"
} |
How does printf( __( ) ); work?
Today I work through a theme to get a better understanding of WordPress and templating. I discovered this:
<?php
printf(
__('Designed by %s', 'Anyword'),
'<a href="
);
?>
I know it shows "Designed by Blub" (Where Blub is linked) But what does the `__()` mean or why is there a string insert? What for is the Anyword?
Can someone exactly explain this line for me? | It's used for translate text.
The second argument is a kind of namespace (called domain here) to retrieve the translation (for example from a dedicated file or something else).
So `Anyword` here, should be the guy behind the template, or the company or what ever that can be a domain/namespace.
**edit:**
The doc from wordpress give more explanation on how to internationalizing a plugin:
* * *
Add this to the Plugin code to make sure the language file(s) are loaded:
load_plugin_textdomain('your-unique-name', false, basename( dirname( __FILE__ ) ) . '/languages' );
To fetch a string simply use `__('String name','your-unique-name');` to return the translation or `_e('String name','your-unique-name');` to echo the translation. Translations will then go into your plugin's /languages folder.
* * *
For your plugin/theme, the `your-unique-name` seems to be `Anyword`. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 12,
"tags": "php, templates, localization"
} |
previous_post_link in same taxonomy in custom post type
I'm trying to make `previous_post_link()` and `next_post_link()` work inside a custom post type, inside a same category (taxonomy) but its not working.
It this posible ?
I'm trying:
<?php previous_post_link('<div class="posts-next">%link</div>', 'Next in category',TRUE); ?> | I'd suggest using a plugin for this. `next_post_link` and `previous_post_link` will use the category taxonomy (literally)*, so they will not work as expected with custom taxonomies, which I think you are using here.
I've used both Smarter Navigation by Scribu and Ambrosite Next/Previous Post Link Plus, which are both great plugins for this sort of thing.
* _See the source for`get_adjacent_post()` which is used by WP's `next/previous_post` functions in \wp-includes\link-template.php to see how "category" is hard-coded._ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, pagination"
} |
Using wp-super-cache and amazon cloudfront - can I serve a file directly (no cdn)?
I'm using the wp super cache plugin with cdn support turned on (aws cloudfront). I'm also using wp tables reloaded. The latter plugin includes a text file via ajax, and that file is being served by the cdn. The plugin doesn't do any sort of jsonp maneuvers, so the file hits access-control-allow-origin issues.
Before I go and mess with the plugin to pull the file correctly, does anyone know how I can restrict the cdn from storing this file, and just serve it up directly? | The CDN tab of wp-supercache allows you to exclude files and folders.
[edited to add]
The field `exclude if substring` allows entry of a comma separated set of strings (eg `.php, wp-include, specialpluginjsfilename`). Any file names that match against this set of values is excluded from the CDN.
So, using the example above the following would be excluded from the CDN
* All .php files
* Any files or any file from any directory that has the string `wp-include` in it
* Any file or any file from any directory that has the string `specialpluginjsfilename` in it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "cdn, plugin wp supercache"
} |
Convert uploaded PNG to JPEG automatically
Is there a way to convert automatically uploaded PNGs to JPEGs and keep the original? In other words, let the user upload a PNG, but show in wordpress (thumbnails, large, medium, etc) the JPEG version and only show the original uploaded PNG when Wordpress request the full image. | There is a way, I recommend you combine the imagefx plugin with a custom function , <
You can read about it here: < , and use a function like one found here: <
It would look something like (not tested):
imagefx_register_filter('custom-name','my_custom_filter');
function my_custom_filter(&$image, $outputFile, $quality) {
$image = imagecreatefrompng(&$image);
imagejpeg($image, $outputFile, $quality);
imagedestroy($image);
}
But remember they are not the same format and .jpg does doesn't support alpha-transparency | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "uploads, post thumbnails, images"
} |
Get Custom post with ID
How do I get a custom post by its ID? I want to display a single post from custom post using its ID. I tried `'post_type' => 'homepage', 'post_id' => '717'` but it didnt work.
Thanks | You simply don't need to specify a `post_type` when calling `get_post()`. The `ID` for any sort of post is _unique_ among the whole DB-posts table. So if you're calling a post with ID = 17
$id = 17;
$post = get_post( $id );
then you'll simply get this single post.
Note, according the Codex, when using `get_post`
> You must pass a variable containing an integer (e.g. $id). A literal integer (e.g. get_post(7)) will cause a fatal error (Only variables can be passed for reference or Cannot pass parameter 1 by reference). | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "custom post types, loop"
} |
Custom Columns WordPress Admin
I am just about finished creating custom columns through the WordPress admin panel.
The custom post type I am using is called "slides". I figured out how to add the column titles and all of the column content (because they're WordPress defaults)...what I am missing is how do I add content to the "thumbnail" column? Some kind of if statement like: if admin-thumbnail exists display the admin-thumbnail image...which sounds simple enough, I just don't know how to add it to that specific column.
The code I have so far is: <
Thanks, Josh | Chris,
I modified the following (and the code is working!): <
I got it here: <
For every column you simply add another case :)
Thanks, Josh | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, wp admin, columns"
} |
Ability to edit image via WYSIWYG
In the wordpress post WYSIWYG, you can easily add images from the media library. But, once the image is inserted into the post, it is not intuitive to edit the image's source to a different image in your media library. You have to remove the image completely, and then add another one in it's place.
So what I am asking is twofold:
1. Can the tinyMCE editor plugins (in this case wpeditimage) be overridden via functions.php or a plugin? Or can I totally override it with my own?
2. Do you agree with me that this is a usability issue in WP, or am I just smoking something?
Any feedback or suggestions highly appreciated | You maybe smoking something, but it doesn't change the fact that you are right ;) WP image management, (or should I say TinyMCE image management) is really sub par.
ImagePro might be a good solution for you. Not only does it help replacing images in editor but also resizes them and displays a server-generated resized version of the image. Anyway, it's nice for what it does. I personally used it on a couple of projects. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "images, tinymce, wysiwyg"
} |
How can I create an automatic drop down menu with my tags?
I have another post type which isn't the default one. I have four taxonomies attached to that post type. And I have many tags attached to these taxonomies.
I would like to create a drop down menu that pull automatically all the tags by their taxonomy.
For example: Post type: Culture Taxonomy 1: Books Under that, all the books (tags) Taxonomy 2: Movies Under that, all the movies (tags) etc..
Thanks! | `wp_list_categories` is what you're after. It takes `taxonomy` as an optional argument.
Example taken from Codex:
<?php
$taxonomy = 'genre';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title
);
?>
<ul>
<?php wp_list_categories( $args ); ?>
</ul> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, custom taxonomy, menus, taxonomy, tags"
} |
How to check if post/page or taxonomy post is published by admin
Example :- 10 users and 2 admin in a site.
If the post is published by admins than
<?php ?????() { ?>
<!-- do this -->
<?php }
else { ?>
<!-- do this if posted by user -->
<?php } ?> | This could be simple as:
global $post;
if ( user_can( $post->post_author, 'manage_options' )){
// this is an admin
} else {
// this is not
}
_Assuming the only admins on your site can manage options._ | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, custom taxonomy, admin, conditional tags"
} |
How to change the label text in default setting pages?
I've seen various tutorials on how to modify the menu items of a Wordpress Site's admin, but I'm trying to find a tutorial or way on how to modify the actual admin page labels. Here's what I mean:
When you are in the back end and you hover over SETTINGS, and click GENERAL, a page comes up with, of course, the general settings for the site. The labels for each input field are as follows: SITE TITLE, TAGLINE, WORDPRESS ADDRESS(URL), SITE ADDRESS(URL), etc.
I'm looking to add a function to my functions.php for a theme that will allow me to change these labels
Is this even possible? Or do I just have to hard code it in? | You can modify the labels using `gettext` filter hook ex:
add_filter( 'gettext', 'theme_change_label_names');
function theme_change_label_names($translated_text){
if (is_admin()){
switch ( $translated_text ) {
case 'Site Title' :
$translated_text = __( 'New Site Title label', 'theme_text_domain' );
break;
case 'Tagline' :
$translated_text = __( 'new Tagline label', 'theme_text_domain' );
break;
}
}
return $translated_text;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "wp admin, labels"
} |
Where can I store common cross-site text (e.g. headings, titles etc.)
I am developing a site that I want to hand over to a client once complete. The core page 'content' is manageable, but there are elements of content (common headings, titles etc.) that are shared across multiple pages & sections within the site, and I would like to give the client a single 'admin page' where they can set all of this information; there are about 25 bits of configurable content - all of them small strings. | You should build a theme settings page for all the "global" settings like social media url:s, phone number etc..
It could be something like this: !enter image description here
Here is a guide how to make a Settings page:
How to build a theme options page.
Or you can make a settings page with the new Customizer that comes with WordPress 3.4 so you can see your updates before you save it:
Look at this video to see what i mean:
And here is how you can do it: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "admin"
} |
Page title in post query
How do i add the current post/page title in a post query?
I've tried this, doesn't work:
query_posts( 'posts_per_page=10category_name=&' . $post->post_title); if (have_posts()) : while (have_posts()) : the_post(); | Your original code has a typo - the ampersand is used to separate arguments, so it should be:
'posts_per_page=10&category_name=' . $post->post_title
However, since this is a new query in addition to the default, a new instance of WP_Query should be used instead of `query_posts`:
$args = array(
'posts_per_page' => 10,
'category_name' => $post->post_title
);
$related = new WP_Query( $args );
if( $related->have_posts() ):
while( $related->have_posts() ):
$related->the_post();
endwhile;
endif; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "query posts"
} |
Advanced Custom Fields: how do I check to see if a value is set in an field?
How do I check and see if a value is set in an Advanced Custom Field? | You can see in the docs that you get the values by `get_field()`, so do something like this:
$values = get_field( 'field_name' );
if ( $values ) {
echo 'A value is set';
} else {
echo 'A value is not set';
}
Change `field_name` to your wanted field. | stackexchange-wordpress | {
"answer_score": 13,
"question_score": -7,
"tags": "custom field, advanced custom fields"
} |
Why does querying on post_tags (which has been applied to custom post types) only return posts?
So I've created a little jquery cycle based feature rotator that pulls from the post_tags. I added the post tags to my other custom post types like this:
register_taxonomy_for_object_type('post_tag', 'reviews');
register_taxonomy_for_object_type('post_tag', 'interviews');
//...
When I add a 'featured' tag to one of my reviews and one of my interviews, and query for it thusly:
$query = new WP_Query( array( 'post_tag' => 'featured' ) );
I get two random posts instead of the two expected results. Any ideas? | Take a careful look at the arguments for `WP_Query`. By default, it queries for the post type `post`.
To select your custom post types, you need to change your query a little:
$query = new WP_Query( array(
'post_type' => array( 'reviews', 'interviews' ),
'post_tag' => 'featured'
) ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, wp query, taxonomy, tags"
} |
How to Get All Taxonomies AND All Terms For Each Taxonomy With Post Count Zero
Is there an easy way of obtaining every registered taxonomy and for each registered taxonomy, get all the terms for that taxonomy, and for each term, get the post count, without actually fetching all of the post data?
I would assume it is most definitely possible. I would also assume it requires some massively long database query using `$wpdb`. | You can do this with just `get_terms` \- this allows you to fetch all (or some) of the terms from one (or more) taxonomies.
By default it excludes 'empty' terms, so you'll need to set the arguments appropriately.
//Array of taxonomies to get terms for
$taxonomies = array('category','post_tags','my-tax');
//Set arguments - don't 'hide' empty terms.
$args = array(
'hide_empty' => 0
);
$terms = get_terms( $taxonomies, $args);
$empty_terms=array();
foreach( $terms as $term ){
if( 0 == $term->count )
$empty_terms[] = $term;
}
//$empty_terms contains terms which are empty.
If you wish to obtain an array of registered taxonomies programmatically you can use `get_taxonomies()` | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 2,
"tags": "terms, wpdb, multi taxonomy query, advanced taxonomy queries, tax query"
} |
Is there an action_filter hook to add content before the post title?
I am looking to add content before the post title but not included in the markup of the title itself so adding to `the_title` doesn't seem to be the right hook for this.
Thanks | No, there is no reliable hook. The markup is provided by the theme, and there unlimited variants. You will have to change the theme’s markup directly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, filters"
} |
How to get both image attachment ID and url
I am using advanced custom fields repeater-field to get the image url like this:
<?php the_sub_field('billede'); ?>
But I also want to get the attachment ID for the image, to be used for something else.
Is this possible? :) | The simplest way to do this is to change your field to return attachment ID instead of URL, and then when you need the URL, use `wp_get_attachment_image_src` with the ID. The only method I'm aware of to get ID from URL is with a custom SQL query. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "advanced custom fields, images"
} |
custom field with links
I want to create a custom field, let's say Tickets in which I can store different links for each post. For example:
On a post page I have a button called "Buy ticket" which has a specific link, also on another post I have the same "Buy ticket" but with another link and so on ... How can I make this ? Thanks | Lets go with an example...
**Custom Field Name:** `buy-ticket`
**Custom Field Value:** `
And you said, you want a button called "Buy ticket" linking to the Custom Field Value. This how you do it:
<a href="<?php echo get_post_meta($post->ID, 'buy-ticket', true); ?>" title="Buy a ticket right away!">
<span>Button text or code here</span>
</a>
**SOURCE:** WordPress Codex Function Reference/get_post_meta
**PS:** You can disregard the `<span>` tag. I used it for cosmetic purposes. :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "custom field, post meta"
} |
Contact Form 7 - add custom function on email send
Just playing around with `Wordpress / Contact Form 7`.
Is it possible / do you know how to **add custom javascript function on successful email send event**? | simply add you JavaScript function to your page then find the **Additional Settings** field at the bottom of the contact form management page and use the `on_sent_ok` JavaScript action hook like so:
on_sent_ok: "MY_JavaScript_function_Name();" | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "plugin contact form 7"
} |
Any plugin or Script to integrate ajax selection module into WordPress page
I am creating a WebHosting site using WordPress. It needs a custom feature selection module to add remove amountof disk space etc.
In this particular website that I like 1), there is a custom "instance selection"-module that adds ram space etc. the site is WordPress powered.
Is there any plugin or script to get the same functionality like that ?
1) It's not the OPs site. | The Site you linked is not using Ajax to update its simply a custom designed **`jQuery UI Slider`** and if you look at the source of the page more specifically at the included `server-order.js` you can see that all of the prices are set in an array and there is no Ajax going on there simply JavaScript. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "ajax"
} |
Remove "posts" from admin but show a custom post
After checking out: <
I successfully use the following code to hide some stuff from the menu:
add_action( 'admin_menu', 'my_remove_menu_pages' );
function my_remove_menu_pages() {
remove_menu_page('link-manager.php');
remove_menu_page('tools.php');
remove_menu_page('users.php');
remove_menu_page('edit-comments.php');
}
However both the "posts page" and a custom post types page seems to run on `/wp-admin/edit.php`.
So I'm looking for a way to _hide_ the posts menubar but still show the menu for a custom post type I've added. | Doing this search, I've found this fine answer by Chris_O. There's even a jQuery solution I proposed there.
Anyway, the function `remove_menu_page('edit.php');` only removes the Posts menu.
But, as we learn from Chris answer, **`remove_menu_page('edit.php?post_type=athletes');`** removes the Custom Post Type menu.
To really block access to the URL, as we're merely hiding the menu item, check the following Q&A: Blocking Administrative Access to Authors and Subcribers? | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 8,
"tags": "custom post types, wp admin, admin menu"
} |
Wordpress plugin compatibility explaination when wordpress releases its new version (theoretical)
Recently i updated my `wordpress` to its latest `version 3.4.1` and noticed that few of my plugins are only compatible upto 3.3 although they are working correctly for my site even with the latest version.
So does that means that i need to disable those plugins and look for the alternatives and these plugins are no more `SAFE` to use or it is something else( i downloaded all plugins from `wordpress.org` ONLY) .
Need a better clarification over this and let me know if some concept i m missing with the up gradation :) . Detailed answer is really appreciated and i will do my part then :) | The compatibility shows just the latest version the plugin was tested on. If WordPress didn’t change the API the plugin will continue working and you don’t have to worry.
Test it. There is no other way to be sure. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, wordpress.org, wordpress version"
} |
pull all posts' meta key values from current category only
I am having trouble figuring out how to pull the meta key values for just one category. I can pull all the meta key values (for meta_key "city") in all categories no problem like this:
$querystr = "SELECT $wpdb->posts.*,$wpdb->postmeta.*
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id AND meta_key = 'city'";
but cannot figure out a way to limit it to a single category. Every time I try to modify the query above with various left and inner and right joins, I get back nothing useful.
Any ideas? Ideally it would filter by the category page we are on, but If I need to create individual category pages, I can deal with that... | Apologies, but my PHP isn't wonderful... but I believe for someone who has some at least average php skill, this will make sense. I cut and pasted this line from a query I am doing against a custom taxonomy myself where I only wanted it to display each term only once.
$terms = array_map("unserialize", array_unique(array_map("serialize", $terms))); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field"
} |
add a menu item to navigation menu to link to external url
I followed this tutorial to add a menu item to navigation menu to link to external site:
<
I copied the snippet of code to my theme's header.php I created a page with the name having the text that I want to appear in the navigation I added a custom field to the page called redirect and placed the link url into the value field.
And then tested and the link never appears in the menu. | Are you trying to navigate to an external page or redirect? (Also, bear in mind that was posted almost 3 years ago...in websites and technology in general, that's an eternity!)
You could always just add a custom link to the WordPress menu under Appearance->Menus. Just make sure you add support in the functions.php file.
<
And here for adding theme support: <
This is how you would add functional support:
//setup the dynamic navigation
if (function_exists(register_nav_menus)){
register_nav_menus(
array(
"main_nav" => "Main Navigation Menu"
)
);
}
Then go to the admin panel->Appearance->Menus, and add your external link there.
Then in your template, you would call it like so:
<?php wp_nav_menu(array('menu' => 'Main Nav Menu')); ?>
This is, ofcourse, what you were looking for | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "navigation"
} |
How to create category page
Anybody could help me to make a category page only. Thank you. | You'll want to stick something like this in your theme's `category.php` file:
<?php
// fetch the categories with the parent being the current cat
$sub_cats = get_terms('category', array(
'parent' => get_queried_object_id()
));
if(!is_wp_error($sub_cats) && $sub_cats)
{
foreach($sub_cats as $cat)
{
// Create your grid here, this is just an example
printf(
'<a href="%s">%s</a>',
get_term_link($cat, $cat->taxonomy),
$cat->name
);
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
WP 3.4 - what action/hook is called when theme customisation is saved?
i'm looking for the action/hook called when saving theme customs colors in the new admin interface?
i need to call a custom function to save a set of php generated images.
if anyone have clues... :)
thanks | The settings are saved via ajax, with the action `customize_save`. In the `wp-includes/class-wp-customize-manager.php` class, the callback for this ajax method is the `save` method (see source)
This triggers the `customize_save` action, prior to updating each of the settings.
Each setting is actually an instance of the class `WP_Customize_Setting` and saving the setting triggers the action
customize_save_{$setting_id}
if you wanted to trigger the action when a particular setting is saved (unfortunately there's no filter).
The `save` method calls the `update` method, which behaves different depending on whether the settings is a 'theme_mod' or 'option'. Regardless they are both saved using `update_option` (and so passed through the appropriate filters). The former is done so via `set_theme_mod()`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 7,
"tags": "theme development, themes"
} |
How to Rename a Template File?
If i have pages that point to `somefilename.php` and want to change the filename to `betterfilename.php`, can I leave the template comments unchanged without manually changing all the pages?
/*
Template Name: Some File Name
*/ | Chris gave me some good insight, and I appreciate the filter func. But I wound up changing the db through phpMyAdmin:
UPDATE wp_postmeta SET meta_value = 'new-filename.php' WHERE meta_value = 'old-filename.php'; | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "templates"
} |
Retrive post by tags PHP code
For example, i am building a cinema site..
For movies - I am using post - The movies are post there.. For actors - I am using post_type : persoane , Taxonomy : lista.
How can i retrive the movies play by bruce willis in <
For example, i have : < This movie have Bruce Willis Tag....( this is a regolar post in wp)
In Bruce Willis page i want to retrive the movie.... that have Bruce Willis Tag
In conclusion i want to display the movies that actor play in
I anny body know please help. Thanks in advance
I try this but no sucess
<?php $args = array(
'tax_query' => array(
array(
'taxonomy' => 'post',
'field' => 'slug',
'terms' => get_query_var('term')
)
)
);
query_posts( $args );
if ( have_posts() ) : while ( have_posts() ) : the_post();
echo get_post_format();
endwhile; else:
echo 'No movie found';
endif;
wp_reset_query();
?> | I think there are multiple issues here:
1) Because you're using `query_posts()` the post object's query_vars are inherited by your new `query_posts()`. I suspect then, that `'post_type' => 'persoane'` is implicitly part of that query posts call. If you switch to using WP_Query instead of query posts, I suspect that will fix the issue.
2) Have you double checked that `get_query_var('term')` is returning what you expect? I think that only works on taxonomy archive pages. Instead, you'll want do use `get_the_tags()`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions"
} |
How do we check if the user is logging in or registering?
I am changing the text on the login page using this filter:
function filter_register_text() {
return "<p class='message register'>Registering for this site will give you access to the admin panel to add new products with images and useful files for others to download and choose open product licenses.</p>";
}
add_filter('login_message', 'filter_register_text');
I just want to show the text if the user **signs up** on the website, not for users who just want to **log in**.
Thanks. | I think your best bet is to check if the `action` parameter is set & equal to `register`:
if ( isset( $_REQUEST['action'] ) && $_REQUEST['action'] == 'register' )
add_filter( 'login_message', 'filter_register_text' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "filters, login"
} |
How do I make specific plugin functionality apply to different sites in a network?
I have a site specific plugin that I've written for the main site in my multisite network. Now I realize that the shortcodes that are in the plugin are also useful on the sub-sites, however the sub-sites don't need all the code for custom post types and taxonomies.
How do I make just the shortcodes work for sub-sites? Is there a conditional I can use? Here's how my plugin is currently set up:
// Plugin Directory
define( 'CLICK_DIR', dirname( __FILE__ ) );
// General
include_once( CLICK_DIR . '/lib/functions/general.php' );
// Post Types
include_once( CLICK_DIR . '/lib/functions/post-types.php' );
// Taxonomies
include_once( CLICK_DIR . '/lib/functions/taxonomies.php' );
// Shortcodes
include_once( CLICK_DIR . '/lib/functions/shortcodes.php' ); | if ( is_main_site() ) {
include_once CLICK_DIR . '/lib/functions/general.php';
include_once CLICK_DIR . '/lib/functions/post-types.php';
include_once CLICK_DIR . '/lib/functions/taxonomies.php';
}
include_once CLICK_DIR . '/lib/functions/shortcodes.php'; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugin development, multisite, shortcode"
} |
Obtain a list of available translations
In answering this question: Change language by clicking a button. It was necessary to obtain a list of languages for which translations were available (i.e. their po/mo files were present in `wp-content/languages`).
## So how can you obtain that list?
Clearly by 'available' we can only mean that their `po/mo` files are present - and it's not a concern if every plug-in also provides a translation for that language (interesting to see how you might do this though).
The list was originally intended for us in a drop-down, whereby a user could select from a list of (available) languages. So the human readable form of the language _as well_ would be a bonus. But I think this is probably not possible.
View the question linked to above for demonstration of the current method used. | You can get a list of available languages with `get_available_languages( $dir )`. It returns an array with all `.mo` files where the names does not start with `'continents-cities'`, `'ms-'` or `admin-`.
To get a readable name for the file use `format_code_lang( $code )`.
If you scan a directory for language files and get an array like `array( 'de_DE', 'tr_TR' )` this function will build ~~translated~~ names for the languages: `German` and `Turkish`. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 6,
"tags": "translation"
} |
Permalinks not working on new site
I'm setting up a new site on 3.4.1 and the Permalinks will not work.
I have deactivated all plugins and switched to TwentyEleven and they still fail.
I can see through outputting $wp_rewrite that the rules are being flushed when I chnage the structure, and .htaccess is being updated, but no matter what I do, I just get a 404 error.
I also notice that it doesn't matter what structure I use (excluding default), all links are in the format of the /%postname%/ structure.
Any suggestions of what else I can try? Thanks. | As I was always getting a server generated error, a friend of mine pointed out that this meant the `.htaccess` file was not even being read.
He advised checking the `.conf` file for the site, and sure enough, there was a typo in the `<Directory /var/www/...>` entry, meaning that the directory was not being read correctly when a user visited the site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks"
} |
Load Javascript from Plugin in One Page Only?
I use the ALO EasyMail Newsletter.
But the plugin is loading lots of Javascript in the head.
I have a mobile site and the scripts are loading in all the pages. I think this affects the mobile performance and want to load it only on the newsletter pages.
How can i do that and load it only in the `/nieuwsbrief` page?
The php starts with:
<script type="text/javascript">
//<![CDATA[
<?php if ( is_user_logged_in() ) { // if logged in ?> | Drop this in your `functions.php` or a custom plugin.
function wpse_57621_alo_tidy()
{
if ( $page_id = get_option( 'alo_em_subsc_page' ) ) {
if ( ! is_page( $page_id ) )
remove_action( 'wp_head', 'alo_em_ajax_js' );
}
}
add_action( 'wp', 'wpse_57621_alo_tidy' );
It's attached to the `wp` hook, which runs just after the request has been handled & queried.
We're saying "if the ALO newsletter page setting exists, but we're not currently on said page, unattach the script output hook". | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugins, php, functions, newsletter"
} |
Wordpress blog code format
I am new to wordpress and I just created a new blog(free version). Now It seems that code fromat doesn't work. All lines are aligned to the left. Please look at the image below.
!image
Thanks. | You need to wrap your code in either `code` or `pre` tags. `code` is for when inline code in a sentence e.g. `include("hello.php")` whereas `pre` is for preformatted blocks of text e.g.:
function hello_world(){
echo 'hello world';
}
For code highlighting etc, you'll need to look for plugins.
The easiest way of using these tags is using the preformatted style:
!enter image description here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin"
} |
Simply Exclude - Category feed exclusion is excluding from category feed instead of just the main feed
I am using Simply Exclude to make sure that certain categories do not show up on the home page and in the sites main feed, < However, excluding the category from the main feed also excludes posts from the category's feed, < How do I get it so that the main feed has these categories excluded but the category's feed remains populated? | It took me a while but I figured it out, I just placed this in mu functions.php file:
function remove_se_filters($query) {
if($query->is_feed && $query->is_category){
global $wp_filter;
foreach($wp_filter['pre_get_posts'][999] as $key=>$filter){
if(strpos($key, 'se_filters') !== false){
unset($wp_filter['pre_get_posts'][999][$key]);
}
}
}
return $query;
}
add_filter('pre_get_posts','remove_se_filters');
I found that I couldn't use the remove filter function because I did not have access to the original class variable that was used to set the filter in the first place so going into the filer's global variable and unsetting the array manually was the next best option. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, rss, filters"
} |
Templates have disappeared from drop down lists
I think this happened when I upgraded to 3.4, or it might have happened more recently. The template drop down list is now missing most of my templates. Pages that were using the templates are still working but when I go to edit the page the drop down says 'Default template' and the template it is currently using is not shown in the drop down box.
does anyone have any ideas why they disappeared or what I can do to get them back? | There was a WordPress 3.4.1 update released a little over a week ago. One of the bugfixes mentioned is "`Fixes an issue where a theme’s page templates were sometimes not detected.`" Have you tried doing that upgrade yet? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "templates, page template"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.