INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Naming script handles right way I was wondering is there any convention or what is the right way for naming handles in `wp_register_script()` and `wp_register_style()` functions? For example if I am developing a plugin that uses modernizer, is it better simply naming it 'modernizer' or something unique like 'my-script-modernizer'? If it is better to have unique handles and I am developing multiple plugins and I'm sure all uses same script. Should I use same handle in all plugins?
This question does to a degree solicit opinionated answers, but I feel it's a good one nonetheless. As far as _my opinion_ goes and the way I handle things is this: Definitely use the same handle for the same script in all your plugins and/or themes. You don't want to load exact duplicates, if two of your plugins are used in the same WP install. I give a generic handle to widely used and renowned scripts such as modernizr. Why should such a script be loaded more than once, under different handles? I prefix handles of my own scripts, for reasons of namespacing.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "customization, wp register script, wp register style" }
How does WordPress search work behind the scenes? I am using WordPress search to search a range of custom post types and allow the user to drill-down into each individual post type. However I'm finding that WordPress is not returning what I'd deem to be the 'best' matches first. For example, if I search for Microsoft, pages that contain the term irregularly are still returned before pages that regularly use the term. Basically I'm trying to find some information on how WordPress ranks pages and determines relevance and if I can influence this **without having to install any plugins**. Any help much appreciated.
**EDIT** \- The current version of WordPress supports relevance, so this answer is no longer accurate. * * * There's no concept of rank or relevance, it's just a simple LIKE query on the post title and content: ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') You can use the `posts_search` filter to modify or completely replace the search query with your own. From `/wp-includes/query.php`: // Allow plugins to contextually add/remove/modify the search section of the database query $search = apply_filters_ref_array('posts_search', array( $search, &$this ) ); Also see the available query filters on the `WP_Query` Codex page.
stackexchange-wordpress
{ "answer_score": 10, "question_score": 13, "tags": "search" }
featured image as background image on pages I'm adding a featured image on my page through the dashboard and I want to use it as a background image on the container div of the page. I want to apply the background image through css, so I am thinking to put a style attribute inside my markup. I'm thinking to make something like this: <div id="<?php echo $post_name; ?>" class="page<?php echo $post_id; ?>" style="background: url(<?php wp_get_attachment_image_src( get_post_thumbnail_id(), 'large' ); ?>) !important;"> But unfortunately this is not working. When I check the output is like this: background: url() !important; What is wrong with this ? Any suggestions? Thanks!
You need to `echo` the return value from `wp_get_attachment_image_src()`. It also returns an `Array()`, so you need to grab the needed part from that array. In this case it's the first/`0` value. Example: <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?> <div id="post" class="your-class" style="background-image: url('<?php echo $thumb['0'];?>')"> <p>your text demo</p> </div>
stackexchange-wordpress
{ "answer_score": 14, "question_score": 10, "tags": "pages, post thumbnails, custom background" }
Add product category to post_class In the content-product.php template, this is the section of the code I am working with (line 43): <li <?php post_class( $classes ); ?>> I need to find a way to include categories as part of the $classes variable, because as of now, it is not echoing the categories into the class, and I need this to do a sort on the products. Any ideas?
Untested, but adapting from the Codex example for filtering the post class... basically changing `get_the_categories()` to `get_the_terms` and accounting for the name of the Product Category taxonomy. // add category nicenames to post class function product_category_class($classes) { global $post; foreach((get_the_terms($post->ID, 'product_cat')) as $term) $classes[] = $term->name; return $classes; } add_filter('post_class', 'product_category_class');
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "categories, plugins" }
query_posts ignores the argument The query_posts totally ignores the day argument. I'm trying this: $day = date('j'); query_posts('day='.$day); if (have_posts()): while (have_posts()): the_post(); //show posts endwhile; wp_reset_query(); endif; What I'm doing wrong?
Don't use query_posts this will alter your main loop, you can query posts by day 1-31 using WP-Query(); $day = date('j'); $args = array( 'day' => $day); $day_query = new WP_Query($args); if ($day_query->have_posts()) : while ($day_query->have_posts()) : $day_query->the_post(); //show posts endwhile; wp_reset_postdata(); endif;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, query posts" }
Why is setlocale() returning false on WPEngine? It appears that WPEngine does not have support for different locale strings, rendering `setlocale()` useless. `setlocale(LC_ALL, "es_ES");` returns `false` and immediately after that, `setlocale(LC_ALL, 0)` (as you would expect from the previous `false`, returns `"en_US"`.
The issue with `setlocale()` is not the function itself. It is that WPEngine _only_ has English language locales installed (the complete list is below) and cannot realistically install any other locales. Because I needed to just print some Spanish language dates (not change the entire WordPress installation to Spanish), I wound up creating an array of the date strings in question and writing a function that parses them if necessary (or sends the result to `strftime()`): The array is here: < The function is here (it gets called just like `strftime()`): < And this is the complete list of WPEngine Locales: en_AG en_AU.utf8 en_BW.utf8 en_CA.utf8 en_DK.utf8 en_GB.utf8 en_HK.utf8 en_IE.utf8 en_IN en_NG en_NZ.utf8 en_PH.utf8 en_SG.utf8 en_US.utf8 en_ZA.utf8 en_ZW.utf8
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "localization" }
are there any downsides to increasing the number of most recent items in a feed The default number of items to show in a rss feed is 10 (Settings-Reading) Is there any reason why I shouldn't show all items. When I use feeds from other sources (not wordpress) it seems like they show all the items. Is there any performance hit on the server for showing a large number of items?
You can increase the number of items safely. Feed creation is pretty fast. It is just a simple loop through the latest posts, no scripts are loaded, no pagination, widgets or other expensive operations. For your subscribers, more items are better, because they can explore your content faster. Make sure to use a full text feed, excerpts are rarely useful.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rss, feed" }
Rewrite url / permalink for default archive - yearly / monthly I want to change the structure of yearly/monthly archive URL of default post type `'post'`. As we know be default the URLs are like: Default: ` but want them rewritten, so end up like this: New: ` i tried following but do seem to work: add_rewrite_rule("about/blog/archive/([0-9]{4})/([0-9]{2})/page/?([0-9]{1,})/?",'index.php?post_type=post&year=$matches[1]&monthnum=$matches[2]&paged=$matches[3]','top'); add_rewrite_rule("about/blog/archive/([0-9]{4})/([0-9]{2})/?",'index.php?post_type=post&year=$matches[1]&monthnum=$matches[2]','top'); add_rewrite_rule("about/blog/archive/([0-9]{4})/page/?([0-9]{1,})/?",'index.php?post_type=post&year=$matches[1]&paged=$matches[2]','top'); add_rewrite_rule("about/blog/archive/([0-9]{4})/?",'index.php?post_type=post&year=$matches[1]','top'); I'd like someone to point to the right direction, need more info do leave a comment. thanks.
You can do this without adding rewrite rules by changing the `$date_structure` of the `$wp_rewrite` instance of the `WP_Rewrite` class: function wpa116030_init(){ global $wp_rewrite; $wp_rewrite->date_structure = 'about/blog/archive/%year%/%monthnum%/%day%'; } add_action( 'init', 'wpa116030_init' ); Visit your Permalinks settings page after adding this code to flush the rewrite rules.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "permalinks, url rewriting, archives, rewrite rules" }
open selected wordpress post with javascript I'd like to create a link that opens the selected post via javascript onclick in the loop. If I use `<a href="<?php the_permalink(); ?>More...</a>` in the loop it opens the correct post. But If I use <script> function open_win() { window.open("<?php the_permalink(); ?>") } </script> <a href="#" onclick="open_win()">More...</a> it just won't open the correct selected post. How can I make this work?
You could use the following: <script> function open_win( thePostURL ) { window.open(thePostURL); } </script> <a href="#" onclick="open_win( '<?php the_permalink(); ?>' )">More...</a> It seems like a bit more work than it's worth though, the following would have the same result of the link opening in a new window: <a href="<?php the_permalink(); ?>" target="_blank">More...</a>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts" }
Does the FD Feedburner plugin create feeds for categories I have setup the FD Feedburner plugin. I want to get feeds for each of my categories. Do I need to manually create feeds for categories in Feedburner? or Does the plugin automatically create feeds for categories. Here is another older link to the plugin
I think this is how it works: You need to manually create feeds in Feedburner.com for categories. You can use a URL like this: feeds.feedburner.com/Lovefood_burgers In wordpress you would create the main feed in the FD Feedburner plugin: feeds.feedburner.com/Lovefood Choose the option: Append category/tag to URL for category/tag feeds ... Now when you select a category feed in Wordpress, it will redirect to the category feed that you setup in Feedburner.com btw, I am pretty sure this is correct. However, I figured this out by experimenting, not be looking at source code or by validation from anyone else (i tried) - so there is a chance I could be incorrect.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "feed, feedburner" }
how to change/remove/hide menu under installed plugins Recently I install one plugin. After installing the "bookingwizz" plugin, the menu added in menu. Under bookingwizz I now have some submenu as well. Now I don't need all those menu items, but want to keep some and change some name and remove some. So how would I do that? I tried to search in that plugins file and also in database, but never found anything. Here's a screenshot of the menu > !enter image description here
### Solution using Codes To hide a menu from a plugin menu, you need to look for the plugin hook. And after finding the hook, `remove_submenu_page()` will help you to achieve the desired task done. Using the hook and the `remove_submenu_page()`, you can remove the submenu exactly from that plugin. For a complete understanding of the whole, refer to the article like: > **The Complete Guide To The WordPress Settings API** \- Tom McFarlin Then to know how to unset something you may refer to this WPSE thread. ### Easy Solution But for an easy solution, you can use **Adminize** , a free WordPress plugin that will assist you to show/hide certain menu and/or services by the admin roles: > **Adminize** \- WordPress Plugin
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, menus" }
how to set context in Wordpress for unit testing I have created a wordpress plugin which converts shortcodes to content based on the entry saved on the dataase: global $wpdb; $post_id = get_the_ID(); $post_content = get_the_content(); $pattern = '/\[zam_tweets page=([0-9])\]/'; preg_match($pattern, $post_content, $matches); if(!empty($matches)){ $tweets_table = $wpdb->prefix . 'zam_tweets'; $result = $wpdb->get_var("SELECT tweet FROM $tweets_table WHERE post_id = '$post_id'"); $content = $result; } return $content; My problem is how do I set the context to be that of a specific post so that I will get an actual post id when using the `get_the_ID()` method. Is this how I'm supposed to go with this or do I just have to specify them as arguments?
If you have phpUnit configured for testing a WP plugin, you can use a test case like this: In your `plugin-directory/tests/Some_Test_Case.php`: class Plugin_Test extends WP_UnitTestCase { /** * @dataProvider post_IDs_and_expected_results */ public function test_something( $post_id, $expected_result ) { global $post; $post = get_post( $post_id ); $plugin_content = call_plugin_function(); // Your function name here $this->assertEquals( $expected_result, $plugin_content, "Content OK for post $post_id" ); } public function post_IDs_and_expected_results() { return array( array( 1, 'expected result for post_id = 1' ), array( 2, 'expected result for post_id = 2' ) ); } } Command line in your plugin's directory: `phpunit ./tests/Some_Test_Case.php`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugin development, unit tests" }
How to edit homepage in Wordpress? I'm gonna add a bit of code/edit my homepage in Wordpress, but I can't find the page's main file to edit. Take a look at this: < This is my homepage. Now look at the page source in your browser. I want to edit these codes. But I can't find it anywhere in the website directory. It seems to be a html file, but can't find anything on the host to edit. I'm a total newbie, so please explain it clear. I'm using WordPress 3.6.1 and Wallbase theme. Thanks.
If it really is the header you want to edit, you can find its source here: > /wp-content/themes/Wallbase/header.php Depending on A) what it is exactly that you want to customize, and B) how your theme is set up and what options it comes with, you might want to try the Theme Options, which can be found in the _Appearance_ menu in WordPress Admin, **if** present (the options, that is). If it is some CSS thing, however, you have to edit the theme's stylesheet: > /wp-content/themes/Wallbase/style.css
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "php, html" }
When someone likes an article on my blog, they are prompted to log in on Wordpress.com I've set up a blog (not a wordpress.com one) on a regular hosting service. I've installed a free theme and jetpack. The problem is, when someone attempts to like a post, they are prompted to log in to WordPress.com. Any clue on how to solve this? I don't get why users should be prompted to login to wordpress when they want to like an article. **Later edit:** I am interested in the regular facebook 'like' and if this comes with JetPack. If not, are there any popular and easy-to-use plugins?
A user must have a Wordpress.com account to use the Jetpack like function. > It’s worth noting that you readers will need to log in to their WordPress.com account to be able to Like one of your posts. Jetpack website: Likes
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "themes, login, plugin jetpack" }
'all' hook and get_option issue code listing: < I ran into a trouble with my plugin. (It is a class based plugin actually) I'm trying to use `get_option` function. When I just make `var_dump(get_option('option_name', 1))` somewhere in `plugin_options` function (you'll see the code listing) - it outputs `int(1)` The problem is that I cannot use `get_option` inside my `log_to` method. The `log_to` method is bound to 'all' hook. So I guess that's why it doesn't work. (even `wp` is not loading at all) Anyone knows the resolution?
`get_option` fires hooks itself so you are triggering a infinite loop (or something similar if not actually infinite). Your callback calls `get_option`, which triggers the hooks used by `get_option`. Each hook triggers the callback again, which used `get_option` which triggers the hooks used by `get_option`. And so on... Get your option value in the constructor, outside of the callback method. That way, when your callback runs it is inadvertently triggering itself. Proof of concept: class WP_Test_Logging_Plugin { static $data = array(); public function __construct() { $this->data = get_option('option_name', 1); add_action( 'all', array( $this, 'log_to' ) ); } public function log_to() { $hook = current_filter(); var_dump($hook,$this->data); } } $ntlp = new WP_Test_Logging_Plugin();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, options" }
Is there a WordPress equivalent to MediaWiki templates I'm new to WordPress and already in dire need of a way to reuse common page content. For example we have 10+ product pages and in different areas of each product's page I want to include a textual statement. In MediaWIKI they have a system of Templates which area awesome! You define a template with the content you want included and then include the template in pages. It's like a pre-processor merge system and will dump the contents of the template into the page where it's called for. The following topics seem to be close to what I want but not exactly * Text snippets shared across posts * Turn a snippet of HTML and PHP into a shortcode I found the Post Snippets plugin and it sounds like it could be a good fit but I wanted to ask here if anyone familiar with MediaWIKI knew of a more appropriate option?
I should have tried the Post Snippets plugin before asking this question - it's fantastic on does just what I needed it to. I ran into one slight issue (for me) where simply extracting Page content to a Snippet did not result in the exact same rendered output. I posted a question on the support forum and you can check that for a solution maybe.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "posts, pages, visual editor" }
wp-admin redirecting to wp-login.php When I enter ` it is redirecting to `wp-login.php` page. I checked the `index.php` of the wp-admin folder and checked the file, it is including `wp-config.php`, `wp-settings.php`, `wp-load.php` of the root folder and some files in `wp-include` folder but I am unable to figure out which function is redirecting the wp-login.php file while entering ` I even checked `auth_redirect()` function.
Each call to an admin page loads the `\wp-admin\admin.php` file. For example, from the `\wp-admin\index.php` file: /** Load WordPress Bootstrap */ require_once( dirname( __FILE__ ) . '/admin.php' ); In that file `auth_redirect()` is called. From `\wp-admin\admin.php`: require_once(ABSPATH . 'wp-admin/includes/admin.php'); auth_redirect(); // Schedule trash collection if ( !wp_next_scheduled('wp_scheduled_delete') && !defined('WP_INSTALLING') ) wp_schedule_event(time(), 'daily', 'wp_scheduled_delete'); set_screen_options(); `auth_redirect()` does the redirect. From the inline docs: /** * Checks if a user is logged in, if not it redirects them to the login page. * * @since 1.5 */ function auth_redirect() { [...] $login_url = wp_login_url($redirect, true); wp_redirect($login_url); exit();
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "login" }
Add a column before username in the users profile table I want to reorder the Company column to be the first column in the table, the code is working fine but it's position is the last one. How can I get it to be in the first before the username? function add_company_column($defaults) { $defaults['company'] = __('Company'); return $defaults; } function view_company_column($value, $column_name, $id) { if ($column_name == 'company') { global $wpdb; $companyID = get_usermeta($id, 'company'); $company = $wpdb->get_row("SELECT com_name FROM " . $wpdb->prefix . "companies WHERE com_id = " . $companyID); return $company->com_name; } } add_filter('manage_users_columns', 'add_company_column', 15, 1); add_action('manage_users_custom_column', 'view_company_column', 15, 3); Thanks
Ok, I solved it by unsetting `$defaults` and reconstructing it after adding the company function add_company_column($defaults) { unset($defaults); $defaults['company'] = __('Company'); $defaults['username'] = __('username'); $defaults['name'] = __('Name'); $defaults['email'] = __('Email'); return $defaults; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, screen columns" }
Display WP posts in 3 responsive columns I'm trying to display 6 random WordPress posts in 3 responsive columns, 2 rows, by using: <?php $the_query = new WP_Query("showposts=6&cat=1&orderby=rand");?> For example, <div class="row-fluid"> <div class="span4"> Random Post 1 </div> <div class="span4"> Random Post 2 </div> <div class="span4"> Random Post 3 </div> </div> <div class="row-fluid"> <div class="span4"> Random Post 4 </div> <div class="span4"> Random Post 5 </div> <div class="span4"> Random Post 6 </div> </div> I'm using WP Bootstrap. Any help would be much appreciated.
<?php $the_query = new WP_Query("showposts=6&cat=1&orderby=rand"); while ( $the_query ->have_posts() ) {$the_query ->the_post(); $i++; if ($i == 1){echo "<div class=row-fluid>";} ?> <div class="span4"> Random Post <?php echo $i ; ?> </div> <?php if ($i == 3){echo "</div><div class=row-fluid>";} if ($i == 6){echo "</div>";$i=0;} } wp_reset_postdata(); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, columns, responsive, twitter bootstrap" }
How do i use the use the wooCommerce functions in a wordpress plugin? How would i use the wooCommerce hooks in my wp plugin? Here is what i am trying to do: add_filter('woocommerce_edit_product_columns', 'pA_manage_posts_columns'); function pA_manage_posts_columns($columns, $post_type = 'product') { global $woocommerce; if ( in_array( $post_type, array( 'product') ) ) { $columns['offering_price'] = __( 'offering price', 'your_text_domain' ); // this offering price title $columns['offering_qty'] = __( 'Qty', 'your_text_domain' ); // add the quantity title } unset($columns['name']); return $columns; } I have included the woocommerce class: $ds = DIRECTORY_SEPARATOR; $base_dir = realpath(dirname(__FILE__) . $ds . '..') . $ds; $file = "{$base_dir}woocommerce{$ds}woocommerce.php"; include_once($file);
I believe, the hook is called differently add_filter( 'manage_edit-product_columns', ... ) The 'woocommerce_edit_product_columns' is not a hook name, but a function name in WC 2.0 As for the access to global $woocommerce - as long as the WooCommerce plugin is loaded, it's available. If, however, your plugin is loaded before WooCommerce (alphabetically), then you can should do something within a function hooked to 'plugins_loaded'.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
Redirect after closing Theme Customizer when user does not have permission for theme page I'm looking for a way to alter the href target for the "close" button from the theme customizer. Another question/answer came very close, but in my case the solution used which involved "load-themes.php" doesn't work because the user in question wouldn't have permission to access that page. ( Wordpress Customizer: custom redirection after closing ) Basically the "Close" button now takes the user to a page that tells them they don't have permission to access it. I'd like it to redirect to the main admin page but I'm not sure how to do that. The other solution mentioned using jQuery, but I have NO clue how to do that. I tried messing around with it for a while but I really have no idea what I'm doing at this point. Any help would be greatly appreciated!
You can try this _jQuery_ script injected via the `customize_controls_print_footer_scripts` hook: /** * Change the url of the Close link in the /wp-admin/customize.php page * See */ function change_close_url_wpse_116257() { $url = get_admin_url(); // Edit this to your needs printf( "<script> jQuery(document).ready( function(){ jQuery('#customize-header-actions a.back.button').attr('href', '%s'); }); </script>" , esc_js( $url ) ); } add_action( 'customize_controls_print_footer_scripts', 'change_close_url_wpse_116257' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, permissions, theme customizer" }
Where to set individual blog quotas? I am administering a self-hosted, multi-site Wordpress 3.1.x site with a few hundred sites. 10 users have requested to have their quotas increased to 1GB. I can't do it for everyone, but I would like to do it for these 10 sites. How can I set blog media quota on a site-by-site basis ? Thanks
Go to your site's Network Admin page -- usually something like `example.com/wp-admin/network/`. Go to **Sites » All Sites**. Mouse over the site that you need to edit and select **Edit** in the menu that appears. Now select the **Settings** tab. Scroll down to the bottom (or near the bottom, depending on whether you have plugins installed that add more settings at the bottom). You're looking for the **Site Upload Space Quota** setting. Put the appropriate number of MB in that box -- if you're updating a site's quota to 1GB, for instance, you'd put `1024` in the box. If there's nothing in the box, it will use your network's default quota.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "multisite, admin, uploads, media" }
wp_mail - Remove sitename from email subject Can someone tell me how to remove site name from the email subject. As of now my email subject looks like this: > **[sitename] - Subject goes here** I want it to look like this: > **Subject goes here** I checked the `wp_mail()` code. There is a `wp_mail` filter available. Can someone tell me how to use that filter to alter my email subject?
Finally, I wrote some code and it worked very well. I hope it helps. Put this in your `functions.php` file //remove sitename from email subject add_filter('wp_mail', 'email_subject_remove_sitename'); function email_subject_remove_sitename($email) { $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); $email['subject'] = str_replace("[".$blogname."] - ", "", $email['subject']); $email['subject'] = str_replace("[".$blogname."]", "", $email['subject']); return $email; }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "filters, hooks, email, wp mail" }
Hook when category is added to post I'm trying to do something when a category is added to post and saved. I thought that using the `save_post` hook would have registered when a category is added to a post, but it doesn't appear to. When I edit a post and do nothing but change the categories for the post, I don't get the `save_post` hook fired (editing the title, body, etc fires the `save_post` hook successfully). Is there another way to use `add_action`/`add_filter` to detect when a category is added to a post?
You may want to try: do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids); You can find it under this Docs and the action is located at wp-includes/taxonomy.php add_action('set_object_terms','wpse5123_set_object_terms',10,4); function wpse5123_set_object_terms($object_id, $terms, $tt_ids, $taxonomy){ if($taxonomy == 'category'){ echo '<pre>'; print_r($terms); echo '</pre>'; exit; } } The code above isn't tested but I think you get the point.
stackexchange-wordpress
{ "answer_score": 11, "question_score": 7, "tags": "categories, hooks" }
custom single.php not working Trying to solve this issue for the past hour and I can't figure out what's going on. Trying to create `single-blog.php` (I have a few posts which are under the category 'blog') but Wordpress automatically redirects these posts to single.php! I've flushed the permalinks by **settings** > **permalink** > **save changes** but still nothing happens. To test & to see if Wordpress picks up on single-blog.php the code I used was: <?php get_header(); ?> <h1>TEST HERE</h1> <?php get_footer(); ?>
Read Template Hierarchy article in the codex, especially pay attention to Single Post Display part. As you can see you have only three options: 1. `single-{post_type}.php` 2. `single.php` 3. `index.php` It means that you can't create a template for posts related to `blog` category. So you shouldn't use `single-blog.php` template, use `single.php` instead and add there something like this: <?php get_header(); ?> <?php if ( has_category( 'blog' ) : ?> <h1>TEST HERE</h1> <?php else : ?> <h1>Else posts</h1> <?php endif; ?> <?php get_footer(); ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "posts, templates, single" }
Database question while Migrating from one domain to another on same WebHost [Bluehost] I am about to migrate WordPress Installation from One Domain to another which are under the same host and have common cpanel. Besides the first step of backing up and moving the WP filesystem, can we just use the same database without exporting/importing it via PHPmyAdmin ?
If your server is not changed, you don't need to do something with your database. Just leave it as it is. Additionally I would like to recommend you to read Moving WordPress article from the codex. You will find all answers on your questions about migration.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, migration, phpmyadmin" }
How to make method from plugin available in theme? Let's say this was in my plugin: class pluginslug_foo { public function bar() { //stuff } } and I wanted to make the method bar available for use outside of the plugin, for instance in a theme file so it could be called with `pluginslug_bar();`. I tried: function pluginslug_get_foo() { $foo = new pluginslug_foo(); return $foo; } function pluginslug_bar() { $bar = $foo->bar; } But I got an unknown variable error for $bar when I tried `pluginslug_bar();` in my theme:(
An alternative way is to use static class methods in plugins, and optionally write functions as alias: ## in Plugin: class Pluginslug_Foo { static $foo = 'Bar!'; public static function bar() { return self::$foo; } } if ( ! function_exists( 'pluginslug_bar' ) ) { function pluginslug_bar() { echo Pluginslug_Foo::bar(); } } ## in Theme: if ( function_exists( 'pluginslug_bar' ) ) { pluginslug_bar(); // echo 'Bar!'; } or if ( method_exists('Pluginslug_Foo', 'bar' ) ) { echo Pluginslug_Foo::bar(); // echo 'Bar!'; } Of course static methods and variables not always fit the scope, and this is a general theoric example: without know your real scope/code is impossible to say if it's good for you or not.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 6, "tags": "plugin development, oop" }
Switch a single site to a multi-site A client of mine wants to switch their single site installation and make it a multi-site one so that they can run an online store on a sub-domain while keeping their existing site on the primary domain. I've Googled all morning but all I can find is ways to import a single site into an already existing multi-site installation whereas what I need to do is convert a single to a multi. Is this possible?
Have you checked out Create A Network on the codex? Essentially: 1. Add `define( 'WP_ALLOW_MULTISITE', true );` to your `wp-config.php` 2. Access Tools > Network Setup from the admin menu & follow the instructions. !enter image description here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, import" }
CSS of the admin panel Where can i get hold of the CSS of the admin panels? Id like to make it look different on my development environment so that no one changes the production server by mistake. Like giving it a different background-color.
One way is to enqueue a style.css for the admin panel. Create a file to say `custom-css.css` and add css to it and then enqueue it to the admin by putting the below in the theme's `function.php` file. function admin_enqueue() { wp_enqueue_style( 'custom_css', content_url() . '/themes/theme-name/custom.css'); //Please replace the path with the correct path to the file in your theme } add_action( 'admin_enqueue_scripts', 'admin_enqueue' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, css" }
Replace the post count on wp_list_categories with "Has Posts" instead of number and "No Posts" if none How can this be achived? Replace the post count on wp_list_categories with "Has Posts" instead of number and "No Posts" if none.
Add the below in your theme's **functions.php**. It should work the way you want function my_list_categories( $output, $args ) { $output = str_replace( '(0)', '(No Posts)', $output ); $output = preg_replace( '/\((\d+)\)/', '(Has Posts)', $output ); return $output; } add_filter( 'wp_list_categories', 'my_list_categories', 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "categories" }
What is the right way to include a wp-admin file in your theme? I'm trying to use `wp_delete_user()` in my theme, to allow a user to delete their account from the front-end. Turns out that the `wp_delete_user()` is not defined unless /wp-admin/includes/user.php has been included. Is there a _right_ way to do this in WordPress? Something that uses get_bloginfo() or a global constant for example?
You need to add `require_once` statement at the beginning of your `functions.php` file: require_once ABSPATH . 'wp-admin/includes/user.php';
stackexchange-wordpress
{ "answer_score": 9, "question_score": 5, "tags": "theme development, wp admin, include" }
Wordpress multilingual site to work with other plugins I have a project in which the client needs the site to support 5 different languages. After some research on Google and here, it's clear the two ways to do it would be either using Multilingual plugins or Multi-site. My question is, if I were to use the wordpress plugins such as qTranslate, how would the other plugins work, i.e slideshows, testimonials etc. For example, most of the slideshow plugins comes with only a single title fields. In that sense, is using plugins for the translation still efficient keeping in mind that I am going to be using sidebars and other plugins which don't support multingual? Or using the Multi-site is the only option?
Use both: a specialized plugin and multisite. There are plugins doing that (I’m the developer for one, Multilingual Press, but there are others). The main advantage is indeed interoperability: you can activate language and theme specific other plugins per sub-site, you don’t get any data hidden in custom post types or post meta fields, and you can use regular URLs, even different URL structures on each site. Be aware, some poorly written themes and plugins will not work with any multi-language plugin. Custom post types and taxonomies registered in themes are really hard to translate, because they aren’t accessible across the network. Also make sure to activate plugins doing that as network plugins, not per site, if you need those translated.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, multi language" }
Multiple loops on a Search result page? I have a custom template that displays search results based on a plugin. The wp_query contains all the taxonomy information to show the proper posts. How can I have two loops on the same results page? The first would contain posts from the query with the taxonomy of `ptype` and the term `featured`. The second loop contains all the rest of the posts from the main query EXCEPT the ones with the taxonomy of `ptype` and the term `featured`. When the posts are queried they are queried through two other custom taxonomies.
Check out the WP_Query() function. You'll be able to run multiple queries and get an array for each post type
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, custom taxonomy, wp query, taxonomy, advanced taxonomy queries" }
Create a body div using CSS I am trying to add a white background to just the body and header text on my blog, so that I can add a background image behind the whole site. I know I need to create a div that sits behind the body and header, however I'm a beginner with CSS so could do with a few pointers if possible. Blog address is www.astridkearneyblog.com Any help would be greatly received! Thanks.
Easiest Solution would be to create a new css rule that simply changes the background color of an element to white i.e: .white-background{ background-color: #ffffff; } Then just add `class="white-background"` to the elements you want to have a white background. Just remember an HTML element can have multiple classes inside a single class="" attribute just add the classes separated by spaces. if you add this class and the background doesn't behave you can add !important to the CSS rule as follows: .white-background{ background-color: #ffffff !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, custom background" }
How to make the home screen of my blog not show full posts? I recently set up my blog and on the home screen, the full blog posts are shown. Is there a way to cut off the blog posts at some point in the text? As it is now, my home screen is extremely long with a bunch of full blog posts.
That is usually dependent upon the theme that you are using. But you can also manually set each blog post to only show so much with the `<!-- more -->` tag that you insert in to each post. If you're wanting to update the theme template file, you'd replace the_content() function call with the_excerpt() function call (see the Codex for details on how to use) in the template file that is being loaded on your home page which depends upon the theme. Could be front-page.php or archive.php or index.php in your selected theme's directory.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, user interface" }
Display site admin profile fields in header.php I am working on a multisite setup and Im trying to display some meta from the site owner's profile. I tried the following code but it is echoing the super admin's meta instead of the current site admin -- <?php $user_id_from_email = get_user_id_from_string( get_blog_option(get_current_blog_id(), 'admin_email')); $current_site_admin = get_userdata($user_id_from_email); $twitt = (get_user_meta($current_site_admin, 'twitter', true)); ?> <?php echo $twitt; ?> Since there will be a lot of sites on the network and only one admin, im trying to retrieve this information dynamically. Any ideas on how to fix this? Thanks
Ok I figured a way to do it. If anyone else is interested, here's the code. It first gets the user id of the admin of the blog, and then it uses the id to pull the meta from the profile fields. For one field -- <?php $thisblog = $current_blog->blog_id; $user_id_from_email = get_user_id_from_string( get_blog_option($thisblog, 'admin_email')); $twitt = (get_user_meta($user_id_from_email, 'twitter', true)); ?> <?php echo $twitt; ?> And to display multiple fields -- <?php $thisblog = $current_blog->blog_id; $user_id_from_email = get_user_id_from_string( get_blog_option($thisblog, 'admin_email')); $twitt = (get_user_meta($user_id_from_email, 'twitter', true)); $fb = (get_user_meta($user_id_from_email, 'facebook', true)); ?> <?php echo $fb; ?> <?php echo $twitt; ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "theme development, multisite, admin, user meta, profiles" }
Can I use `.phtml` instead of `.php` I want to use `.php` extension for php that have a logic like `functions.php`, and for a html template file `.phtml`. Is there way to use `.phtml` instead of `.php` extension? For example, `sidepar.phtml`, `page.phtml` and so on.
I'm going to echo all of the above comments & say it's not a good practice to get into. You might want to borrow a convention from the PHPTemplate library used in Drupal and call your files `something.tpl.php`. That way it's still a `.php` file, but you have an extra extension showing it's a template.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php" }
Website needs to be opened for wp_mail to work I have a custom post type `Events`. In that post type, I can schedule events with a date and time. Whenever I publish an event, it will automatically send an email to the users 2 days before the event. However, I noticed that in order for the script to work, I need to have the wesite running. Is my assumption correct? I can't seem to find anything in the Codex regarding this. How do I fix this? I am using a plugin called wp-delayed-mail
This plugin uses WordPress CRON API. Its no the same thing as usual CRON jobs available at cPanel dashboard. The difference is in the way how they are executed. When somebody visits your site, WordPress checks if there is a scheduled job which has to be run, then WordPress runs this job by initiating a separate request to a specific URL. If nobody visits your site, then your CRON jobs won't be run even if they are already overdue... In other words to run WordPress CRON jobs in time you have to have visitors on your site. Another option would be to ping your site by using special service...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, wp mail" }
Unable to run jQuery script in my template file I really want to run a simple code in my template file. E.g. if I put somethign like this in my page.php: <script type="text/javascript"> jQuery(document).ready(function($) { alert("Hello world!"); }); </script> It's not working. But simple javascript is working: <script type="text/javascript"> alert("Hello world!"); </script> **Why is jQuery blocked in WP to be included in template files?** and maybe more important question > **WHERE IN THE WP SETTINGS CAN I RE-ENABLE THIS?** I know I can use wp_register_script etc. but in my scenario I need to paste simple javascript code in the template files. **How to allow load jQuery code snippets in WP template's file too?** And why is it even blocked?
I don't think jQuery script is en-queued by default with WordPress templates. So you should place the jQuery script in the header/footer for your code snippet to work.
stackexchange-wordpress
{ "answer_score": -2, "question_score": 0, "tags": "jquery, templates, javascript" }
MySql Query for Wordpress I need to count the number of value 1 from wp_ul_locked on wp_usermeta i try this code $wpdb->get_var("SELECT COUNT(*) WHERE 'meta_key' LIKE 'wp_ul_locked'"); or `$wpdb->get_var("SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '1'")`; or $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->usermeta LIKE 'wp_ul_locked' WHERE meta_value = '1'"); but return empty or error !example of table Where is my error?
Try it like this: $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->usermeta WHERE `meta_key` = 'wp_ul_locked' AND `meta_value` = '1'");
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, mysql" }
How to change the post title to h1 Here's a quick question: how do you change the post title to be h1 instead of h3 as it is by default? Can it be done from the CMS or from the actual code? Is there a plugin for this? Thanks and let me know if I need to edit my question before downrating!
theme specific it is, maybe look into themes `single.php`, search for title, or a function call of `the_title()`
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "seo" }
Get 1 more post in loop In a simple loop, for example: $loop = new wp_query(array('posts_per_page' => 3)); while($loop->have_posts()) : $loop->the_post(); if(get_post_meta($post->ID, 'skip_me', true) == true){ // do something to ask for one more post, // as we really want 3 total! continue; } else { the_content(); } endwhile; If a certain condition is met, we might pass over a post, but what if we still _really_ want to get exactly 3 posts? Rather than arbitrarily asking for extra posts and then stopping after 3 successes - is there any other way to ask of the loop, to get one more post? I suppose with this exact example the easiest thing would be to do a `meta_query` within the arguments. But what if it weren't that easy?
You should probably add a meta query to your `WP_Query()` args: $loop = new wp_query( array( 'posts_per_page' => 3, // Meta Query 'meta_query' => array( array( 'key' => 'skip_me', 'value' => 'true', 'compare' => '!=' ) ) ) ); Or you could perhaps go with the simpler version in this case: $loop = new wp_query( array( 'posts_per_page' => 3, // Meta Query 'meta_key' => 'skip_me', 'meta_value' => 'true', 'meta_compare' => '!=' ) ); In both cases, posts that have the meta value "true" for "skip_me" will not be included in the queried object.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "loop" }
Removing short versions of category archive URL I'm looking after a site where someone has configured /%category%/%postname% as the Permalink structure. A side-effect of this seems to be that a category archive will appear both at the usual /category/foo and also /foo. One downside of this is that it creates a duplicate page. Another is that any "Older posts" link on that second page won't work, since it will point to /foo/page/2 which will return a 404. Is there any way to _disable_ the /foo version of the page without changing the Permalink structure?
I suppose there's a way to remove the offending rewrite rule from the rules array, maybe on `generate_rewrite_rules`, which would result in I'm not sure what, maybe a 404, or WordPress would try to redirect to the correct URI. or, I came up with this bit of code to check for category requests without `category` in the URL, and 301 redirect them to the version with `category`. It's a bit crude, but it may work for you. function wpa_category_requests( $request ){ if ( ! is_admin() && isset( $request->query_vars['category_name'] ) && ! isset( $request->query_vars['name'] ) ){ if ( false === strpos( $request->request, 'category' ) ){ wp_redirect( home_url( '/category/' . $request->query_vars['category_name'] . '/' ), 301 ); } } } add_action( 'parse_request', 'wpa_category_requests' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, permalinks" }
How to allow hidden custom fields to be added from wp-admin/post.php? I know that using an underscore in front of a custom field name hides it from display on the front-end, e.g. `_custom_field_name`. In my experience, WordPress also prevents one from adding such a custom field on the front end. Before I go spelunking around core, I wanted to ask: Is there an "easy" way to allow `_custom_fields` to be added from wp-admin/post.php? The reason is this: we rely on hidden custom fields, but when troubleshooting production issues in prod it would be useful to be able to inject certain hidden post meta. I'm not a fan of touching the production database by hand. !what i get
I found the following filter, here unlocking all protected meta data: add_filter( 'is_protected_meta', '__return_false' ); Or it can be fine tuned: add_filter( 'is_protected_meta', function( $protected, $meta_key, $meta_type ) { $allowed = array( '_edit_lock', '_test', '_wp_page_template' ); if( in_array( $meta_key, $allowed ) ) return false; return $protected; }, 10, 3 ); It allows to display the meta data as well as insert new ones (globally or fine-tuned).
stackexchange-wordpress
{ "answer_score": 12, "question_score": 5, "tags": "posts, post meta" }
How to make the_tags title translatable? How can I make the text in the_tags function translatable? Currently I'm using following: <?php the_tags('<div class="tags">Post Tags',' ','</div>'); ?> But I'd like to make 'Post Tags' text translatable by adding the text domain, similar to this: _e('Post Tags', 'textdomain');
Translate the title before you send it to `the_tags()`: the_tags( '<div class="tags">' . __( 'Post Tags', 'textdomain' ), ' ', '</div>' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme development, translation" }
Style file inclusion I am trying to include a `flexslider.css` file with this code: wp_register_style( 'flexslider', get_template_directory_uri() . '/css/flexslider.css' ); if( is_page( 'home' ) ) { wp_enqueue_style( 'flexslider' ); } but it is not working this way, any idea why? trying to solve this one for a whole day.
You need to hook it to an action. Add the below code to the theme's **functions.php** file. It should work. add_action( 'wp_enqueue_scripts', 'theme_flexslider_css' ); function theme_flexslider_css() { wp_register_style( 'flexslider', get_template_directory_uri() . '/css/flexslider.css' ); if( is_page( 'home' ) ) { wp_enqueue_style( 'flexslider' ); } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, wp register style" }
Notification to Admin or Author upon new post I am using a custom function with 'publish_post' hook for a notification to the author when the post has been published but the issue I am facing right now is that the notification is being sent out twice and as well when the post is updated. Here is how my function looks. function authorNotification($post_id) { $post = get_post($post_id); $author = get_userdata($post->post_author); $message = " Hi ".$author->display_name.", New post, ".$post->post_title." has just been published at ".get_permalink( $post_id ).". "; wp_mail($author->user_email, "New Post Published", $message); } add_action('publish_post', 'authorNotification'); am I missing something here?
You need to write your hook for `transition_post_status` action: function authorNotification( $new_status, $old_status, $post ) { if ( $new_status == 'publish' && $old_status != 'publish' ) { $author = get_userdata($post->post_author); $message = " Hi ".$author->display_name.", New post, ".$post->post_title." has just been published at ".get_permalink( $post->ID ).". "; wp_mail($author->user_email, "New Post Published", $message); } } add_action('transition_post_status', 'authorNotification', 10, 3 );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "posts, publish, notifications" }
What is meant by __('page','twentytwelve') I'm using twentytwelve theme with 1.0 version. I saw many codes like following, 'name' = __('page','twentytwelve'); If I give, 'name' = 'page'; It's also working fine. Then why using `__()`? What is use of that?
> Internationalization and localization (commonly abbreviated as i18n and l10n respectively) are terms used to describe the effort to make WordPress (and other such projects) available in languages other than English, for people from different locales, who use different dialects and local preferences. `__()` is used when the message is passed as an argument to another function. `_e()` is used to write the message directly to the page. More detail on this @ <
stackexchange-wordpress
{ "answer_score": 14, "question_score": 5, "tags": "themes, localization, theme twenty twelve" }
the_title(); works in a page template, outside the loop. Why? Trying to wrap my head around the loop concept... Given a template page (page-work.php) with just this code: <?php the_title(); ?> WP correctly shows the title of that page. As I understand it, this is outside any loop and shouldn't work (Codex says to use `get_the_title` in those cases). So the question is, why does it work? Funnily enough, this won't output the title + content, just the title: <?php the_title(); the_content(); ?> Thanks!
The global `$post` object exists already for singular views before `wp_head` is called. It is just not filled with all data. The `the_title()` calls `get_the_title()` which in turn calls `get_post()`. And _that_ calls `$GLOBALS['post']` if no post ID has been passed. See also Generating the ogp tags in theme for a use case.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "loop, get the title" }
Show content based on page number I have a post that I would like to split in to 5 pages and depending on which page the user is on the image at the top of the page needs to change. So page 1 of the Post displays the image in custom field image_1, then page 2 displays the image in custom field 2 and so on... I've set up my custom fields for the post but can't find reference to the function for detecting what page the user is on so I can add the function in to my template, what is the function I should be using?
Current post page can be detected using `get_query_var('page');`. note that if you do not pass any page the page 1 is shown, but `get_query_var('page');` will be `0`; So in your `function.php` you can add: function get_page_image() { global $post; if ( ! is_object($post) || ! isset($post->ID) ) return; $page = get_query_var('page'); if ( empty($page) ) $page = 1; $field = 'image_' . $page; return get_post_meta($post->ID, $field, true); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pagination, page template" }
image_resize() with blank space Any way to resize an image without crop and add new blank space? Using image_resize() from wordpress.
First of all pay attention that `image_resize()` function is deprecated! Use `wp_get_image_editor()` instead of it. This function will return an instance of `WP_Image_Editor` class (or WP_Error if some issues appear during loading your image). This class has `resize` method which accepts three arguments: desired width, desired height and crop flag. Sample usage: $editor = wp_get_image_editor( '/path/to/file.png' ); if ( !is_wp_error( $editor ) ) { $editor->resize( $desired_width, $desired_height, true ); // true - do crop, false - don't crop } Back to your question. Unfortunately there is no way to do what you want to do. Your image aspect ratio doesn't equal to desired aspect ratio, that is why whitespace appears. If you crop the image, you will loose parts of your image from top and bottom, but in this case you won't see whitespaces...
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images" }
Link to file in plugin directory from wordpress template? I know that plugins and theme files should be kept separate but for for internal use I need to do it this way. In my themes header.php file I want to include a php file which just contains html, from my plugin directory. The path is basically /wp-content/plugins/my_plugin/my-html.php I can't seem to figure out the proper code for wordpress to look in the plugins directory, and grab the my-html.php file from within the my_plugin folder. I want to include this file so the html in it is included in the header.php within my theme. What would be the best way to go about this??
In your main plugin file just define a constant containing the path of the plugin: $pluginpath = plugin_dir_path( __FILE__ ); define('MY_AWESOME_PLUGIN_PATH', $pluginpath); After that in your `header.php`: include(MY_AWESOME_PLUGIN_PATH . 'html_file_name.html');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, templates, template include" }
Wordpress and Conditions this might sound stupid to most dudes around, but, I have this code: <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php if ( in_category('123') ) { ?> <div class="pdfbox"> <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> <p>&nbsp;</p> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('pdfs'); ?></a> </div> <?php } else { ?> <div class="pdfbox"> <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> <p>&nbsp;</p> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('pdfs'); ?></a> </div> <?php } ?> <?php endwhile; else: ?> <?php endif; ?> The thing is, how to add another category, like if is category 1 then output, HTML, if 2 the next html, if 3, so on so on.. Thanks!
What you might be looking for here is the elseif statement... <?php if ( in_category('123') ) { ?> <div class="pdfbox"> <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> <p>&nbsp;</p> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('pdfs'); ?></a> </div> <?php } elseif ( in_category('125') ) { ?> <div class="pdfbox"> <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> <p>&nbsp;</p> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('pdfs'); ?></a> </div> <?php } ?> { ?> Hope that helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php" }
output the debug lines to the end of the page Does anyone know a hook, which doesn't depend on the template. A hook I can rely on in any situations? there's some debug data collected while loading pages (i'm using 'all' hook to collect filter names) i would like to log to the screen. i need the data displayed, say, before </body> tag. Thanks.
Use the `shutdown` hook. It runs very late-- "just before PHP shuts down execution" per comments in the source. Proof of concept: add_action( 'shutdown', function() { echo 'This runs very late in the page load'; } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Is $page a global variable in wordpress? I am having a problem with a local $page variable, especially when using it in The Loop. Is it a reserved variable of Wordpress? Also where can I find a list of all those global variables?
Yes. It is an "inside the Loop" global. > $page (int) The page of the post, as specified by the query var page. > > < It is setup and used by `setup_postdata` which executes at every iteration of a standard Loop. Though meant for use inside the Loop, the variable would still be set after the Loop to the last data it was given (unless specifically unset and I don't think it is, but am not swearing to that).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "globals" }
How to set "lang" attribute for post/page title? I am creating multilingual website in Urdu & English lanugage on Wordpress. Major part of site is in English. Only article's body (i.e paragraph & headings etc) are in Urdu. To assign Urdu fonts to urdu content, when writing article, I just switch to HTML Mode and insert lang="ur" attribute with elements and style them in CSS by :lang() pseudo selector. Now I get problem that how I can specifie lang attribute for Post/Page title? Any idea? I hope you will understand what I want to say. Thanks
There is a `the_title` filter. You should be able to wrap the title in a `<span>` using that. add_filter( 'the_title', function($title) { return '<span lang="ur">'.$title.'</span>'; } ); A version compatible with an older PHP: function lang_attr_wpse_116733($title) { return '<span lang="ur">'.$title.'</span>'; } add_filter('the_title','lang_attr_wpse_116733'); If it were me, I'd add a checkbox on the post edit screen somewhere and then wrap both the title and the post body with a `<span>` or `<div>` based on that single checkbox.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "title, language, custom header" }
Set featured link not showing I created my own custom wordpress theme now i am able to add media to my site but the "set featured" link does not show, please i need some help on this.
your theme needs to support Post Thumbnails to have the featured image meta box... Add this to your functions.php file: add_theme_support( 'post-thumbnails' ); See <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, post thumbnails, media" }
Displaying shortcode output through Options Framework I'm hoping someone might be able to help me. I'm using the Options Framework Plugin to customise my site, but I'm having difficulty with using a shortcode in one of the custom fields. I've created an 'editor' field, and called it in my theme like so: <?php if ( of_get_option('footer_contact_form') ) { echo of_get_option('footer_contact_form'); } ?> But it outputs the shortcode (gravity forms) as raw text, like so: < Is it possible to achieve what I'm trying, or will I have to hard code the form into the theme? Many thanks in advance!
You should check out the WordPress function `do_shortcode()`. You can use it to generate the shortcodes, in a string variable, like this : <?php echo do_shortcode( $content ) ?> So in your case, please try: <?php if ( of_get_option('footer_contact_form') ) { echo do_shortcode( of_get_option('footer_contact_form') ); } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "shortcode, options, framework" }
Why does WordPress add 0 (zero) to an Ajax response? Unless I end Ajax processing function by `exit()` or `die()`, the Ajax function receives desired and correct output but following by `0`. Any idea why is that happening? Is that meant to be like that or it could be fixed? add_action('wp_ajax_get_homepage', 'get_homepage'); add_action('wp_ajax_nopriv_get_homepage', 'get_homepage'); function get_homepage(){ echo "get_homepage ->"; exit(); } I've read at AJAX in Plugins, but why is that necessary?
The default response from `admin-ajax.php` is, `die( '0' );` ...by adding your own `wp_die()` or `exit()` or `die()` after returning your desired content prevents the default response from `admin-ajax.php` being returned as well. It also generally means that your ajax call has succeeded. Ultimately, to answer your question, it's meant to work this way. What you are doing by exiting after returning your content is the right thing to do.
stackexchange-wordpress
{ "answer_score": 37, "question_score": 20, "tags": "plugin development, functions, ajax" }
Woocommerce category description as subtitle I'd love to place the category description just after the main title in a span, like a subtitle. add_filter ('woocommerce_page_title', function ($title) { // what should be here? $title .= "<span class='subtitle'>{$description}</span>"; return $title; }); Thanks.
There is an extra hook you can use for this `woocommerce_archive_description`, hook into it like this: add_action( 'woocommerce_archive_description', 'wc_category_description' ); function wc_category_description() { if ( is_product_category() ) { global $wp_query; $cat_id = $wp_query->get_queried_object_id(); $cat_desc = term_description( $cat_id, 'product_cat' ); $subtit = '<span class="subtitle">'.$cat_desc.'</span>'; echo $subtit; } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins, categories" }
Show only 1 term of a current posts taxonomy I've been using this code to display the taxonomy term of the current post. $terms = wp_get_post_terms($post->ID, 'custom_cat'); foreach($terms as $term){ print_r($term->name); unset($term); } Which is fine, except now I have some posts with 2 or more terms associated with them and it's throwing off my layout. Is there a way that I can show only 1 of the terms?
This is more PHP than WordPress, but `wp_get_post_terms` returns a numerically indexed array, so all you need is basic PHP array syntax to grab the first item. $terms = wp_get_post_terms($post->ID, 'custom_cat'); print_r($terms[0]->name); You don't specify which item you want. This will get you last item: $terms = array_pop($terms); print_r($terms);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy" }
How do I add text in a shortcode? I think this might be an easier question but I can't figure it out. How can I add simple text inside a short code? For example: $return_string .= '<a href="'.get_permalink().'"><div>'.read more.'</div></a>'; So, I don't just want to return text, but I want to return text and a link. I am using this shortcode to query the posts, but I want to add a "read more" link after each excerpt, but I cant figure out how to just add the text "read more." Any help would be appreciated!
hello you can try this // Add Shortcode function text_shortcode( $atts , $content = null ) { // Code return '<div>' . $content . '</div>'; } add_shortcode( 'b', 'text_shortcode' ); The shortcode will be something like this [b] content [/b]
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, shortcode" }
Accessing two databases wordpress I'm trying to access a second database with my wordpress system. To do this, I've attempted to follow the advice found here which seems to have worked for a lot of people. In summary, I'm adding the following line to my functions.php: global $newdb; $newdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); $newdb->show_errors(); Unfortunately, when I add this I come up with the following error: > Fatal error: Class 'wpdb' not found in /home/mine/www/wp-includes/functions.php I'm sure I must be missing wrong (obviously, right?) but the instructions don't seem to have any extra steps that I've been leaving out. Thanks for any help
When enhancing WordPress functionality, always use the theme's `functions.php` file (located, generally, in `{WP root}/wp-content/themes/{your theme}/functions.php`), or put your code into a plugin. The rules for hacking core code are similar to the rules for optimization. 1. Don't do it. 2. (for experts only) Don't do it yet.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "functions, database, wpdb" }
In which version of WordPress was the new gallery shortcode implemented? As of WordPress 3.5, as I'm sure you all know, the gallery shortcode generated from the media uploader changed and now includes a list of image IDs. The gallery shortcode codex page says the following: > "It's important to note that this style of gallery shortcode is not new to 3.5, however it is much easier to generate and manage with the new Media Workflow introduced in 3.5." Does anyone know what the minimum WP version is, in which this style of gallery shortcode will still work?
The file `/wp-includes/media.php`, where the Gallery Shortcode is defined, first appears in WordPress 2.5. It has the **`id`** (singular) attribute to refer to the `post_parent`: $attachments = get_children("post_parent=$id ... * * * The **`ids`** (plural) attribute appears in WordPress 3.5, and is used to `include` attachments: if ( ! empty( $attr['ids'] ) ) { $attr['include'] = $attr['ids']; } ... $_attachments = get_posts( array('include' => $include * * * PS: I've updated the Codex, now it reads (updates in bold): > _**Since WordPress 2.5** and up until 3.5, the gallery shortcode [...]_ > [...] > _It's important to note that this style of gallery shortcode is not new to 3.5, **previously we could use the`include` attribute**._
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "gallery, wordpress version" }
Exclude taxonomy term from all loops, but having it on widget I have excluded a custom post type taxonomy term from all posts like this: add_action( 'pre_get_posts', 'exclude_category_posts' ); function exclude_category_posts( $the_query ) { $taxquery = array( array( 'taxonomy' => 'product_cat', 'field' => 'tag_ID', 'terms' => array( 157 ), 'operator' => 'NOT IN' ) ); $the_query->set( 'tax_query', $taxquery ); return $the_query; } But I need that taxonomy term to be included back in a specific widget loop and only for that specific widget. Is there any chance for that? The reason I followed the above way, because I have created a product category, which I'd like to be shown only on a widget I created and nowhere else except search queries and the taxonomy term page. On all other loops I'd like it excluded.
Looks like you've excluded a taxonomy _term_ , not the whole taxonomy. Is that what you intended? But on to the answer... Right before your query in the widget add: remove_action( 'pre_get_posts', 'exclude_category_posts' ); And then you probably want to put it back again after that query by repeating: add_action( 'pre_get_posts', 'exclude_category_posts' ); That is a bit of a "dirty" method and assumes that this is your site and your widget. You may need something more complex if circumstances are different from that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, wp query, loop, query, exclude" }
Put an extra check box on "Page Attributes" widget that will add `lang="ur"` attribute in page's main `<body>` tag. How I can do that? I try different plugin including polylang, but look not working. Please suggest plugin if you know or do some simple coding.
You can create a custom field, give it a value of **lang='ur'** and check for it in your header.php. 1. Add the custom field from the Custom Fields box. Let's call it **page_lang**. Give it a value of **lang='ur'**. **In header.php** : <?php global $post; $lang = get_post_meta(get_the_ID(), 'page_lang', true); ?> <body <?php body_class();?> <?php echo $lang;?>> Each page you want to show this lang, you just select the ' **page_lang** ' custom field and give it the value you want (you have the option to write any value you want, thus any other language than 'ur').
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "multi language, page attributes" }
How to get links to user and tag by its name? For example i have the name of user or the name of tag. Is it possible to get direct link to the author or tag? I need something like `get_permalink` for posts.
Use the `get_user_by` and `get_term_by` functions: // user $user = get_user_by( 'login', 'someuser' ); if( $user ){ echo get_author_posts_url( $user->ID ); } // tag $term = get_term_by( 'name', 'Sometag', 'post_tag' ); if( $term ){ echo get_term_link( $term ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, tags, author" }
Unnecessary url $alt_text = get_post_meta( $id, '_wp_attachment_image_alt', true); $output .= '<div class="pslide"><a href="' . $alt_text . '"><img src="' . $img_attr[0] . '" /></a></div>'; With the code i can get an image and alt text as url for each slide in my slider. Everything works just fine but unfortunately when i move my mouse over the image i can see something like this: 192.168.1.100/wordpress/www.youtube.com How can i get rid of wordpress url ? Thanks in advance !
Always include ` in your URLs. Change `www.youtube.com` in ` or even better ` If you forget the ` then the data is being parsed like it is another page on your website rather than an external website, that's why you'll see `192.168.1.100/wordpress/www.youtube.com`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls" }
Database for development While building plugins one of my biggest annoyances is that my development machine does not match a real world install. What I mean here is that my databases are lacking. I'll code something thinking it'll work (since it does during development) then find out it doesn't because I neglected a minor detail missing from my local db. Even my own online install doesn't contain a full database. Is there available a set of db's pre-filled out with the usual WP content? Or even a script to auto add rows and columns? I'm looking for user's of varying roles, custom post types, taxonomies, comments etc, which can be dropped in for development purposes only? If not does anybody have a backup from an old site they would like to share?
I think you are looking for the Theme Unit Test data: < Download the `.xml` file and import with the WordPress importer plugin, and you should be good to go.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin development, database" }
What does it mean by "Home page / Archives" in JetPack Site Stats? !JetPack Stat Site visit Stat In the JetPack SiteStats, on the "Top Posts & Pages" the first page or link got most views (8) is the **Home page / Archives**. What does it actually denote? JetPack support says: > **Top Posts & Pages** > This section of stats will list the Posts and Pages which have received the most views. A view is only counted for a post or page when the permalink URL is visited. For example, if a visitor reads a post titled “Hello World” while viewing the home page of your blog, the view will not be counted towards the post, only towards total views. As the last line says, the home page won't be counted here, only the Permalink URLs will be counted. Then, which Archive does it mean? A category archive, a tag archive, a day archive, a month archive, a year archive -- there are a lot of possibilities.
My understanding is that it counts the hits for the homepage and all archive pages, specifically the ones you mentioned.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "seo, plugin jetpack" }
Show Nav Link To Users Signed In Wordpress let's users apply CSS classes to links under Appearances-->Menus. Well based off of this, I would like to know if there is a way to hide links that have a certain CSS class. So say I apply the CSS class > .members to one of my navigation links. The catch is, I would like this link to only show to users that are logged in. I am a little stuck though as I don't know how to exactly go about doing this. Could something like: if(is_user_logged_in()) { } I just don't know how I could target a CSS class.
You could use the `body_class` for this purpose, for example: .members { display: none; } body.logged-in .members { display: block; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, css" }
How to completely hide a Wordpress/BuddyPress Install? I want to make a bbPress application hide the fact that it is WordPress or bbPress for that matter. Please do not get me wrong. I am very proud of WordPress however I just do not want to make it easy for someone to snoop on my assets and version numbers etc for security purposes. I have looked at some plugins that seem to do it for classic wordpress but was looking for a recommendation when it came to buddypress. Also I thought about renaming the theme folder etc. Any tips?
Please see: < Sold 2300 copies ;)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin recommendation, bbpress" }
Compare WP Custom Field date I had create a custom field "date" with this format 16/09/2013 (d/m/Y). How can i compare date and show only post with date from today ? This is my query that don't work !! $args = array( 'posts_per_page' => 100, 'meta_key' => 'date', 'orderby' => 'meta_value', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'city', 'value' => 'London', 'compare' => 'LIKE' ), array( 'key' => 'date', 'value' => date("Y/m/d"), 'compare' => '>=', 'type' => 'DATE' ), ) );
Take a look at meta.php:777: ... CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})... So if you want to use DATE comparisons, you should use MySQL compatible date formats (YYYY-MM-DD). Change this part of your code: array( 'key' => 'date', 'value' => date("Y/m/d"), 'compare' => '>=', 'type' => 'DATE' ), to: array( 'key' => 'date', 'value' => date("Y-m-d"), // <- change 'compare' => '>=', 'type' => 'DATE' ), and it should work just fine.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom field, wp query, date time" }
Add a link to the Admin menu I would like to add 2 lines to the POSTS menu in the wordpress admin: Published and Scheduled. I would also like to add a section to the media menu for Unattached media. How would I go about doing this? Cheers!enter image description here
You can intercept the global `$submenu` var and add the desired elements: add_action('admin_menu', 'add_custom_submenus', 999); function add_custom_submenus() { global $submenu; $submenu['edit.php'][] = array( __('Published'), // menu title 'edit_posts', // menu cap 'edit.php?post_status=publish&post_type=post' // menu link ); $submenu['edit.php'][] = array( __('Scheduled'), 'edit_posts', 'edit.php?post_status=future&post_type=post' ); $submenu['upload.php'][] = array( __('Unattached'), 'upload_files', 'upload.php?detached=1' ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "admin, admin menu" }
Custom section (e.g. Demos or Downloads) On my website, I want to display a page where I will store all my demos, which should function just like a blog (so I can add new records, edit them and specify custom meta data and list all of them on a public page), but it should independent for easier management. I have searched the web for answers or tutorials, but haven't any. Example can be found here: < As you can see there there is a separate blog and the demos page function as an independent group of records, with their special metadata and I'm pretty sure there is a way of creating something like this.
You can just create a page template and register a custom post type with its own categories, tags and pretty much everything. You then loop these custom post type entries in your custom template page. < < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization" }
Changing from localhost:8888 to localhost I have just changed ports on MAMP from :8888 to :80 for localhost in order to setup a WordPress multisite for local development. However I have several sites with separate installations that are in my htdocs folder and previously used localhost:8888 as a root. I did the following things in order : 1. Opened wp-config and changed the Mysql hostname to `define('DB_HOST', 'localhost');` 2. Went to the options table of the database and changed the siteurl and home. 3. I cleared my .htaccess file 4. Cleared my browser cache. Still, when I am at the index for localhost I am still being redirected to localhost:8888. I'm sure other people have had this problem and yet I can't seem to find the same question. Interestingly enough I have access to admin just not to the front end.
You need to treat this just like you would when changing domains. The short version is: 1. You need to change the WordPress Address and Site Address in Settings->General. You have to change both 2. Or edit `wp-config.php` to alter the same values as in step #1. This one is easiest if you've already lost part of the site functionality. 3. And alter the hard-coded addresses in the DB. I have always used Velvet Blues Update Urls for that. The Codex has a link to a helper script and a longer 15 step process. Read through that carefully before beginning.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, wp config" }
register_sidebar_widget is deprecated since version 2.8 I have an elderly WordPress theme that I am trying to bring back up to date. I am stuck on the following snippet... if ( function_exists('register_sidebar_widget') ) register_sidebar_widget(__('Pages'), 'widget_nav'); This is giving me the following message... register_sidebar_widget is deprecated since version 2.8! Use wp_register_sidebar_widget() instead I realise that reigster_sidebar_widget has now been replaced by wp_register_sidebar_widget() but I can't work out whats changed with the syntax.
Well... register_sidebar_widget( $name, $output_callback, $classname ); vs. wp_register_sidebar_widget( $id, $name, $output_callback, $options, $params, ... ); It is simple enough to check the Codex entries for each: * < * < Beyond that, I am not quite sure what the question is. You might want to look into the `register_widget` function instead of either of those, though.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "sidebar" }
Get author and excerpt from URL Trying to be tricky here, I want to show a list of articles with their author and excerpt. I'm using a custom field and want the user to just be able to list the URLs on their own line and that's it. Is there a way to look up the non-rewritten url based on the friendly one? Then just pull the article ID from there via regex? To further clarify: Say this is the URL < Can I take it back (decode) to? < So I can grab the 123 and use that to find the author and excerpt.
There is a function called `url_to_postid` $id = url_to_postid( get_permalink(40) ); // $id will be 40 Actually (WP 3.6) it works only for standard posts and page, but with WP 3.7 it will also work for custom post types.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "php" }
Display more than 10 posts on author.php file it seems that there are only 10 posts being displayed on author.php file. The theme I'm using have just this in author.php file:- <?php while ( have_posts() ) : the_post(); ?> <?php endwhile; ?> <?php wt_pagination(); ?> The loop is getting only first 10 posts (of the author). How can I change it to first 30 posts. Without writing a secondary (custom) loop.
when you use the loop the number of post displayed is choosen fron the option set in _Settings->Reading_ in you backend. It affects all the standard loops, not only the author page. To change only for author page you have to use `pre_get_posts` hook and set the wanted number of posts using `posts_per_pag`e argument: add_action('pre_get_posts','change_numberposts_for_author'); function change_numberposts_for_author( $query ) { if ( ! is_admin() && $query->is_main_query() && is_author() ) { $query->set('posts_per_page', 30); // 30 is the number of posts } } See also is_author() on Codex
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, pagination, author, author template" }
Select custom post by meta value Say I've got the custom post type `foo` with a meta box called `bar`. I've posted an entry with `bar` = `pineapple`. Now I want to check if there is a `foo` in the database with a `bar` set to `pineapple`. How would I do that? I've managed to get this working using a `wpdb` query but that doesn't feel right. Is there an elegant, maybe built-in way for me to do this?
I think you mean a query like this one: $args = array( 'post_type' => 'foo', 'meta_key' => 'bar', 'meta_value' => 'pineapple', 'posts_per_page' => 1, ); $query = new WP_Query( $args ); You can check out further information here on _meta queries_ in `WP_Query`. If you only want to check if there exists such a post, you can use the `found_posts` property: if( $query->found_posts > 0 ){ // do stuff } or the usual way with the `have_posts()` method: if( $query->have_posts() ){ // do stuff }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, metabox" }
How to use wp_nav_menu with hashtag links? I am developing a custom theme and the navigation part uses hashtags (yes, all content is on one page). So when i use wp_nav_menu( array( 'theme_location' etc the menu items links to the pages. Can i use/edit wp_nav_menu so it adds a # for every page link, like mysite.com/about-us/ becomes mysite.com/#about-us/ Or should i create a custom menu function? bonus question: Why doesn't wp_get_nav_menu_items give me the permalink/slug for post_name but just the post number as post_name? (see <
You already hinted it yourself: When you look at `wp_get_nav_menu_items()` you'll see that the resulting Array of items gets mapped over with `wp_setup_nav_menu_item()` \- in other words, this function gets applied to each and every nav menu item. In there you can hook into the `'wp_setup_nav_menu_item'`-filter with its `$menu_item` argument, or use one of the filters in the applied functions in between. The level of control just lays in what you use where (look up source). The argument itself is an object that you can influence.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Get plugin directory from a theme Does anyone know a non-hacky way of getting the plugin directory path from within a theme's functions.php? I've used plugin_dir_path( **FILE** ), but because its called in the theme's functions.php it returns the path to that file. Not the plugins directory. I could string manipulate it and add the plugins path, but that feels nearly as bad as hardcoding the whole path. I have got it working using: require_once( ABSPATH .'/wp-content/plugins/ehu-events/event-widget.php' ); But I know that's so oldschool and wrong and I'd probably be shunned from the wordpress community for using it! Is there a standard wordpress function I can use for this?
Maybe what you're looking for is : WP_PLUGIN_DIR // full path, no trailing slash WP_PLUGIN_URL // full url, no trailing slash See documentation
stackexchange-wordpress
{ "answer_score": 19, "question_score": 9, "tags": "plugins, plugin development" }
How to calculate total number of comments made by a particular user When I use the following custom query $wp_comments = $wpdb->get_results("SELECT COUNT(*) FROM wp_comments WHERE userid=$userid") If I use print_r(wp_comments) I get the following printed Array ( [0] => stdClass Object ( [COUNT(*)] => 10 ) ) 10 is the count I am expecting, how to print out the value? Is there any other way to get the number of comments made by the user on the whole site?
You can use `get_comments` function to retrive the comment count.Pass the user id of perticuler user as an argument. $args = array( 'user_id' => 1, // use user id 'count' => true //return only the count ); $comments = get_comments($args); echo $comments Please refer below link for more information. <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 0, "tags": "plugins" }
Sticky Posts Not Sticking to Top of Category Archive I'm using my index.php to display post archive pages rather than a specific archive.php file. This works fine, however sticky posts do not stick to the top of it. They do however, stick to the top of the posts page. Are sticky posts not supposed to stick to the top of archive pages? Here is the code for the loop I'm using; loop-index.php \- < Am I doing something wrong? Or is this just default functionality?
By default, sticky posts only stick to the top of the first page of the main blog posts index. The easiest way to show sticky posts in other contexts is probably via a custom loop, e.g.: $sticky_posts = new WP_Query( array( 'post__in' => get_option( 'sticky_posts' ) ) ); if ( $sticky_posts->have_posts() ) : while ( $sticky_posts->have_posts() ) : $sticky_posts->the_post() ); // Loop markup here endwhile; endif; // IMPORTANT wp_reset_postdata(); You would place that before your normal loop output, and wrap it in any conditionals that you might need (to account for context, pagination, etc.)
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "categories, archives, sticky post" }
How to solve Woocommerce Memory Limit I have Woocommerce set up to run on WP multi-site with my PHP Memory Limit set to 256M in the php.ini I also have in my wp-congif.php define("WP_MEMORY_LIMIT", 128); However Woocommerce shows the following "WP Memory Limit: 12 B - We recommend setting memory to at least 64MB." How can I solve this
You could also try toying with the max memory limit. I think it's far more likely you are on an EIG host and throttled to a 64mb limit. Oh one more thing, it's define( 'WP_MEMORY_LIMIT', '128M' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, plugins, limit" }
W3 Total Cache Minification - Any way to not use php? I use nginx, php5-fpm and fastcgi_cache. W3TC minification seems good enough, but every include points to "minify.php?". I want to be able to keep my site up even if php and mysql server's goes down - surviving on cached (stale) versions of my pages. Is there any way to not touch php for serving minified assets? I mean its already minified and probably gzipped, why does it need to go through .php? I am missing something? My links look like this: <link rel="stylesheet" type="text/css" href=" media="all" />
Yes. You are missing the rewrite rules that'll prettify the URLs of the minified assets. Follow the instructions available for your setup at **WordPress Dashboard** > **Performance** (W3 Total Cache menu) > **Install**.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin w3 total cache, nginx" }
Post/Page Publish/Update button not clickable once I make an edit I open a page and make an edit and the update button becomes grayed out. I have to copy all page content, refresh the page and paste it back in the page, only then does the update button become clickable. It does update the page so there is no issue with that. Only when making the initial edit is in not clickable. Update: I was able to recreate the issue, **but not faithfully**. It seems to occur when the page is trying to auto save. It would begin to autosave and then hang. I don't even know where to begin with this one. Has anyone encountered something similar?
Once I realized it was an issue related to the Page/Post autosave, and not something to do with pasting the data from a text editor, I disabled all plugins to determine if that would be the cause. Disabling the plugins did not seem to have an effect. No errors were reported in the browser error console. I **manually updated the Wordpress installation** and this seems to have fixed the issue. Unfortunatley I do not understand why, none of the files replaced were ever edited by me.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 5, "tags": "posts, pages, post editor, wp update post" }
Retrieve New user's ID I'm trying to retrieve the user id of a new user as soon as they're created. I tried using the hook "user_register" but there appears to be no id in there...maybe it grabs the data before a userID is created? Anyway, if anyone could recommend a hook that would serve this purpose, I'd appreciated. Many thanks!
The only argument you get on `user_register` is the user ID. add_action( 'user_register', function( $user_id ) { echo $user_id; }); Maybe there is an error in your code?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, hooks, user registration" }
W3 Total Cache + S3 + Cloudfront. For a small site, what WordPress/site files normally go into the S3 bucket in order to get optimal use as a CDN?
> what WordPress/site files normally go into the S3 bucket in order to get optimal use as a CDN? Normally the defaults should suffice i.e., You'd want to check these options under the "General" section: * Host attachments * Host wp-includes/ files * Host theme files * Host minified CSS and JS files * Host custom files And under "Advanced" section: * Modify "Theme file types to upload" to something like this: *.css;*.js;*.gif;*.png;*.jpg;*.ico;*.ttf;*.otf,*.woff,*.eot,*.svg That should do it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin w3 total cache, cdn" }
How to I make my post title link to a custom field I have a custom field in my posts called `post_bookmark_url` which contains a link. I want the post title that is displayed in the excerpts on my home page to link to the `post_bookmark_url` rather than the permalink of the post. (I am doing this to create a Drudge Report type of aggregator.) How can I make the "post title" in the excerpts on the home page link to a custom field?
I assume that the post title markup looks something like so: <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> You merely need to replace `<?php the_permalink(); ?>` with your post custom meta value: <?php $post_bookmark = get_post_meta( get_the_ID(), 'post_bookmark_url', true ); ?> <h1><a href="<?php echo $post_bookarmk; ?>"><?php the_title(); ?></a></h1> Other caveats: * You'll want to consider the _context_ in which you use this code. If you only need it in your **Blog Posts Index** , then create a `home.php` template file, and put it there. That way, your post titles are not impacted in other contexts. * You'll probably want to use some fallback in case `post_bookmark_url` isn't set.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, title" }
How do I count how many top level categories there are? I need to calculate some dynamic CSS based on how many top level categories exist. (NOT how many posts are in a category, or how many categories a post belongs to... Nothing about posts at all, just how many top level categories there are) I am new to PHP, but I couldn't find any WP functions that would return the number I'm looking for. Thanks in advance for any help.
As the Codex says, this is the code block to query for only the Top Level categories — the parents. With this, I used the PHP function `count()`. <?php $args = array( 'parent' => 0, 'hide_empty' => 0 ); $categories = get_categories( $args ); echo count( $categories ); ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "categories, count" }
How to add images to taxonomy terms? Could it be done or not? E.g. I want to be ble to upload an image when creating a new taxnomy term. So, when I create a new term called **Mercedes** in my custom made taxonomy called **brands** how can I add a file picker field to that term so I can upload an image of Mercedes logo? Is it even possible to upload a file for taxonomy?
There was actually a plugin written for this a while back - <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, taxonomy, advanced taxonomy queries" }
How to remove custom post type archive I have a custom post type called "recipe" with the `has_archive` parameter set to true. Visiting mysite.com/recipe/ gives a basic archive list of all the recipes posted and a page title of "Recipes". So far so good. Now I'm looking to disable that recipe archive page (but keep individual recipe links working). My first thought was to try setting `has_archive` to false, which sounds like it should do the trick. Nope. The only difference this makes is the page title which for some reason becomes the name of the site. The actual archive is still displayed. What is the best way to actually remove that archive completely? Is there a parameter of `register_post_type` that will achieve this or is it impossible and a case of a custom page template with a redirect in it? Thanks.
The `has_archive` parameter for `register_post_type()` does exactly what you expect it to do. However, it modifies rewrite rules when set. So, if you change it to `false`, you'll need to **flush your rewrite rules** in order for the archive index display to be removed entirely.
stackexchange-wordpress
{ "answer_score": 35, "question_score": 19, "tags": "custom post types, custom post type archives" }
Exclude parts of default css import I'm importing Twenty Thirteen's default stylesheet, but I want it to leave my buttons alone. I could of course disable all mentions of "button" in the temaplate's `style.css`, but that would only work until the next update - I suppose. Is there any way to exclude the styling of certain elements from being imported?
Make a copy of Twenty Thirteen's default stylesheet and remove all unnecessary styles. After it import this copy instead of Twenty Thirteen's and after next update you won't loose your changes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, import" }
date_query seems to be ignored by wp_query I'm altering my main wp_query in a pre_get_posts filter in order to improve my site search capabilities. I've successfully achieved searching in taxonomies, but I fail when it comes to the post date ranges. Even the example query in the wp docs don't work for me. $datequery = array( array( 'after' => 'January 1st, 2013', 'before' => array( 'year' => 2013, 'month' => 2, 'day' => 28, ), 'inclusive' => true, ), ); $query->set('date_query', $datequery); If I print_r the content of `$wp_query->request`, it doesn't contain anything related with dates, except for the ordering. What's wrong? PS: WP 3.6.1
There is no `date_query`, not yet, or not in your version of WordPress. From the Codex: date_query (array) - Date parameters (available with Version 3.7). 3.7 has not been released, though you can get it via SVN, and you are using 3.6.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp query, query, date" }
How do I get a meta value from WP_Query? I've got the custom post type `foo` with meta fields called `bar` and `baz`. Now I get the `WP_Query` object using: $args = array( 'post_type' => 'foo', 'meta_key' => 'bar', 'meta_value' => $bar_value, 'posts_per_page' => 10, ); $res = new WP_Query($args); Now I want to check if the value `baz` of the selected post is equal to `$baz_value`. How can I do that?
I've found a solution to my problem myself. Since none of the already existing answers solved the problem, I figured I could best post mine here to help people with similar problems. The solution: if($res->have_posts()) { $id = $mail_res->posts[0]->ID; // blindly assuming there is only 1 post having baz = baz_value $true_baz = get_post_meta($id, 'baz')[0]; if($true_baz== $baz) { //success } else { //error } } else { //error }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "custom post types, wp query" }
Is there a tool to get the GPS data from a Wordpress blog on a map? There is a guy biking through the world. He is writing a wordpress blog about it. Most of his posts have a GPS coordinate at the bottom. I was wondering if it would be possible to draw a (red) line on a (google?) map perhaps. So you can follow the route this guy is going. Thanks
Depending on what level you want to work. You can try exploring Leaflet. It's a really powerful mapping tool. I think Wordpress might have some tools to help you work with it. See here: < You could also look into KML and such, but it's time consuming.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "map" }
Making pages in a menu appear conditionally How do I make a page (dis)appear conditionally in a menu? I had something like this in mind: if(condition) //show_page_in_menu I would prefer an answer that doesn't incorporate an external plugin.
You can use `wp_nav_menu_objects` or `wp_nav_menu_items` hooks to add your filter function. function my_hide_menu_items($objects) { if ( is_admin() ) return $objects; foreach ( $objects as $k=>$object ) { if ( YOUR CONDITION ) { // if $object shouldn't be displayed unset($objects[$k]); } } return $objects; } add_filter('wp_nav_menu_objects', 'my_hide_menu_items', 10, 2);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, pages" }
Widget header unique classes I have created the code below for one of my widget sections. Currently I am able to manipulate the title bar with (h3.home-widget-header) which is good. But obviously it will be for all widgets in that section. There is 1 or two widgets that I need to style the positioning of the title bar slightly different. My question is - is this possible and how would I go about writing a unique class so I can manipulate each widget in that section individually. Thanks ahead of time! * Mike if ( function_exists('register_sidebar') ) { register_sidebar(array( 'name' => 'Homepage Widget Area', 'before_widget' => '<li class="home-widget">', 'after_widget' => '</li>', 'before_title' => '<span class="home-widget-header"><h3 class="home-widget-header">', 'after_title' => '</h3></span>', )); }
please study the RELATED links here in the right sidebar. < refer to this line: 'before_widget' => '<li id="%1$s" class="widget %2$s">', `%1$s` outputs an id specific to the widget type; `%2$s` outputs a widget specific class including an unique number.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, customization, widgets" }
Plugin to install a plugin I'm wondering if there is a way for a plugin to install other plugins directly. That means, I provide an interface for the user to click multiple plugins and download and install them directly to wp-content/plugins. Basically imagine a marketplace plugin within wordpress where users can purchase plugins FROM a plugin and install directly into their site. I would like to find out the API or any ideas on how to achieve the installation/upgrade.
You can take a look at TGM-Plugin-Activation plugin. It should give you good starting point. As written in the documentation: > TGM Plugin Activation is a PHP library that allows you to easily require or recommend plugins for your WordPress themes (and plugins). It allows your users to install and even automatically activate plugins in singular or bulk fashion using native WordPress classes, functions and interfaces. You can reference pre-packaged plugins, plugins from the WordPress Plugin Repository or even plugins hosted elsewhere on the internet.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins, installation" }