INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to add a php custom page to Wordpress I want to create a custom page for my Wordpress blog that will execute my php code in it, whilst remaining a part of the overall site css/theme/design. The php code will make use of 3rd party APIs (so I need to include other php files) How do I accomplish this? N.B. I do not have a specific need to interact with the Wordpress API - apart from including certain other php libs I need I have no other dependencies in the PHP code I want to include in a WP page. So obviously any solution that didn't require learning the WP api would be the best one.please help me to slove this problem.
Please refer to the **Page Templates** section of the **Static Pages** Codex entry. Essentially, you create a custom page template, named something like `template-foobar.php`, which will live in your Theme's root directory, or in a one-deep sub-directory. Inside this template file, add the following: <?php /** * Template Name: Foobar */ get_header(); // YOUR CUSTOM PHP GOES HERE get_footer(); ?> Now your template is available to be assigned to any static Page you create.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, pages" }
Restrict access to specific users Is there a built-in function that would allow me to restrict access to registered users until the official launch date in Wordpress 3.4.2? The blog is self-hosted.
This should do it. Place it in your theme's `functions.php` or a plugin. function tst($a) { if (!current_user_can('edit_posts')) { wp_die('You are not allowed to view this page'); } } add_filter('template_redirect','tst'); You can still get to the login page like normal by going to "/wp-login.php" or "/wp-admin". Alternately, you could use `wp_safe_redirect` or `wp_redirect` instead of `wp_die` to send people to a "Coming soon" page or something like that.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "content restriction, user access" }
Is there any danger in deleting all transients? I have a big site for a client, and as it is a really customized wordpress installation with lots of extensions on functionality, I can't use the caching plugins. To improve the performance, I built a lot of the Site using transients (for example the navigation, the google maps with all the markers etc.), and leave the dynamic content dynamic. The problem here is if I change anything, I have to manually delete the specific transient to see the current result. The site shows different menus and googlemaps when entered from a different channel, so I have like ten transients for each area. Would you create a function where I delete those all at once (with a listing of the names of the transient), or is it okay to just delete all the transients on the site? It's not really that urgent, but for future ddevelopment I would like to know if you had any problems with stuff like that, and how you manage all your transients. Cheers, fischi
For development I would advise to always work with `WP_DEBUG` set to `true` and do the following: $key = 'transient_key'; if( !WP_DEBUG && ( false !== ($transient = get_transient($key)) ){ /* Generate transient manually */ $expiration = 24*60*60;//How long to keep for set_transient($key,$transient, $expiration); } In general - it should be fine deleting transients, as they should never be assumed to be in the database.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 9, "tags": "transient, cache" }
Admin Subpages without Menu entry I have added some pages to the WP-Adminmenu, with `add_menu_page` and `add_submenu_page`. The URLs for those pages look like `admin.php?page=my-plugin/admin/submenupage.php`. If I try to add a page now that has isnt registered to the menu and link to it with `<a href="?page=my-plugin/admin/add.php">` I'm getting a permissions error. Is there a way to add pages to the admin area without registering them to the menu?
The best thing you can do here is to call them with a `$_GET` parameter, and just register the first site to the menu. so for example, when you registered `admin.php?page=my-plugin/admin/submenupage.php`, you have the `submenupage.php` structured like this: if ( !isset( $_GET['section'] ) ) { include('mainpage.php'); } else if ($_GET['section'] == 'hiddenpage1' ){ include('mainpage.php'); } // go on for every page needed. This way you have your registered menuentry, but by clicking it from the adminmenu you always get to the `mainpage.php`. Just add the `&section=hiddenpage1` or whatever you call your hidden pages, and you will see the "hidden" admin sections.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, wp admin" }
Making the wordpress login form a jQuery dropdown I'm using a plugin called `sidebar-login` to display a wordpress login form (it uses `wp_login_form`) in my sidebar. However, I feel like it the actual form (textboxes and labels) take up too much space and I'd like to hide it all in a slide-down jQuery div. Basically, the user would click on a link called `"Login"`, which would make the login form fade in and slide down for the user to use. The problem is I need to add that link and wrap up the whole form in a div that I can apply a jQuery rule to. What is the recommended way of doing this so I don't break any existing login procedures?
Try using SimpleModal Login. This should be exactly what you are looking for.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "jquery, login, forms, wp login form" }
Return one unique custom post type result when it shares a custom taxonomy in WP_QUERY? Is it possible to remove custom post types from WP_QUERY that have a same shared custom taxonomy so that only one custom post type associated to that custom taxonomy is returned? Example: Get an Items custom post type, returning only one Item per a custom taxonomy. On a taxonomy-types.php page, I'm using WP_QUERY to get the Items custom post type. Then, wp_get_object_terms to get the Models custom taxonomy for the Items, and displayed that. However, I can end up with duplicate Models displayed because WP_QUERY is returning all Items and not one Item per unique Model. Thank you for your help!
Thanks guys. I think I may have found a solution. What I did: * On `taxonomy-types.php`, get all Items for that type using WP_QUERY. * Loop through them, use `get_the_terms()` to get taxonomy Model for each Item * Still in the loop: use PHP's `in_array()` function and a `$model_ids` array for unique Model checking * Still in the loop: if the Model is unique, store the Item id in an `$item_ids` array * End that loop * Use WP_QUERY to get Items with `'post__in'` set to the `$item_ids` array
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, custom taxonomy, wp query" }
Using save_post to replace the post's title I am using custom posts, and in these, I don't a need for the title. This causes Wordpress to set the titles of my posts to "Auto Draft". I'd like to change the title's value to something else, computed from other fields in my post. How do I go about doing that using save_post or some other means?
This simplest method would be to edit the data at the point it's inserted, rather than updating it afterwards, using `wp_insert_post_data` instead of `save_post`. This works on creating a new post or updating an existing post without change. It also avoids the danger of creating an infinite loop by triggering `update_post` within `save_post`. add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 1 ); // Grabs the inserted post data so you can modify it. function modify_post_title( $data ) { if($data['post_type'] == 'rating' && isset($_POST['rating_date'])) { // If the actual field name of the rating date is different, you'll have to update this. $date = date('l, d.m.Y', strtotime($_POST['rating_date'])); $title = 'TV ratings for ' . $date; $data['post_title'] = $title ; //Updates the post title to your new title. } return $data; // Returns the modified data. }
stackexchange-wordpress
{ "answer_score": 24, "question_score": 26, "tags": "custom post types, save post" }
Merging Wordpress posts from different databases I have development and production versions of my website (on the same hosting). I want to easily synchronize the content between these versions. On the production website, content is updated daily. I cannot use the XML export function because duplicate posts would be created on the development website. Currently both websites uses different databases, but if there is a solution that allows for usage of only one database I gladly will go through it.
If you never send/sync Production posts to live. Then just pull/copy the live database to the development database via mysqldump (or similar) and use wp-config vars to force the site and blog URL. Use the following in the dev versions wp-config.php to force the URL's define('WP_HOME',' define('WP_SITEURL', ' You may as well sync the entire database, rather than just posts, so then you get all the post revisions as well as any plugin configurations/data. This is my normal method of developing a live site, locally. (Grab live DB drop Dev DB import Live DB into Dev) (The only fun bit is sending specific plugin configs up to the live site from the dev site)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "database, customization, production" }
How to delete custom field "suggestions" from dropdown list When you use a standard custom field in WP you have to write the name of the cusotm fields the first time. The second time you use a custom field it sticks to the custom fields dropdown list. But, sometimes when you install plugins they ise ALOT of custom fields. This list becomes a bit long an it may "push" som of my custom fields out of tghe list. So, does anyone know how I can remove custom fields from my dropdown list in any easy way?
You can filter the query for these keys on`'query'`. I would start that filter as late as possible to avoid side effect. Sample code, **tested** : add_filter( 'postmeta_form_limit', 'wpse_73543_hide_meta_start' ); function wpse_73543_hide_meta_start( $num ) { add_filter( 'query', 'wpse_73543_hide_meta_filter' ); return $num; } function wpse_73543_hide_meta_filter( $query ) { // Protect further queries. remove_filter( current_filter(), __FUNCTION__ ); $forbidden = array ( 'the', 'keys', 'you', 'want', 'to', 'hide' ); $where = "WHERE meta_key NOT IN('" . join( "', '", $forbidden ) . "') "; $find = "GROUP BY"; $query = str_replace( $find, "$where\n$find", $query ); return $query; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "custom field, database" }
Why does running get_the_excerpt() when generating JSON file take 28 seconds vs. 599 milliseconds without it? I am using the following code to generate a JSON feed. I need to extract the excerpt from posts, but when I run get_the_excerpt() it takes 28 seconds (yes SECONDS!) to run on my local server versus 599 milliseconds when I change get_the_excerpt() to 'hi'. Does anybody have any idea why this is taking so long and what I can do to get it to load faster? This is on my local web server on the computer I'm using so it isn't due to a network issue. $json = array(); while ( have_posts() ) { the_post(); $yo = array('title' => get_the_title(), 'excerpt' => get_the_excerpt()); } $json[] = $yo; $json = json_encode($json);
The problem will likely be a (very slow) callback that is attached to your `get_the_excerpt()` function. To inspect the attached callbacks, just inspect the global: // Best hooked to `shutdown` echo '<pre>'.var_export( $GLOBALS['wp_filters']['get_the_excerpt'], true ).'</pre>'; Then get rid of all those callbacks.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, excerpt, feed, performance, json" }
frontend show edit profile with selected custom options So I have many custom user profile fields. When I use `do_action( 'show_user_profile', $profileuser );` hook it displays all custom user profile fields.. But I would like to show only certain fields. For example add_action('show_user_profile', 'add_extra_profile_fields1'); function add_extra_profile_fields1() { // add extra profile fields to user edit page } add_action('show_user_profile', 'add_extra_profile_fields2'); function add_extra_profile_fields2() { // add extra profile fields to user edit page } Now is there a way to display only `add_extra_profile_fields2` using `show_user_profile` hook?
You could either find the hook that is outputting all those extra fields and use `remove_action` on it. Or you can just create your own hook: do_action( 'my_theme_show_user_profile', $profile_user );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks, actions, profiles" }
How to add to cart via AJAX Woocommerce I have been searching for a while, this. I want to add an item via AJAX. When you add an item to a cart in Woocommerce the page reloads with the GET parameter `add-to-cart="The current product ID"`. I want to do it via AJAX. In the admin area is a checkbox to enable that featured that is labeled "Enable AJAX buttons to add to cart on the product list" But it doesn't do anything, it stills reloading the page.
are we talking about the single product view or the product archive pages (shop,categories)? because the text beside the checkbox/option states, roughly translated: _»activate ajax-checkout-button on product archive pages«_ and on all the installations i did so for, that is the way its working - ajax checkout on the archives, but not on the single view. the latter you have to implement yourself or maybe you find a free plugin for that. * * * _Follow up:_ A basic example on how to use AJAX for the »add-to-cart«-functionality of woocommerce can be found here: Woocommerce - Add a product to cart programmatically via JS or PHP.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 6, "tags": "ajax, plugins" }
Add custom field automatically (add_post_meta) with value based on number of words of article In this topic our friend @toscho created a function that sets the font size according to the number of words in the post. Based on this function, I want to create a custom field whose value will be set depending on the number of words in the post. For example, if the post contains up to 200 words, automatically create custom field (add_post_meta) with value = 1; If your post contains more than 200 words, create custom field with value = 2. Any idea is welcome. Thank you.
Hook into `save_post`, count the words, and update the post meta field. Sample code, not tested: add_action( 'save_post', 'wpse_73563_save_word_count', 10, 2 ); function wpse_73563_save_word_count( $post_ID, $post ) { if ( ! current_user_can( 'edit_' . $_POST['post_type'], $post_ID ) ) { return FALSE; } $count = t5_word_count( $post->post_content ); update_post_meta( $post_ID, '_word_count', ( 200 > $count ? 2 : 1 ) ); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, custom field, post meta" }
Registration and Login form I am creating practice website in which i have "register Here" and "login" link on which I want to open a registration form on click of Register Here and Login Form on click of Login. How can I do this?
Go with Theme My Login. Well written and very functional
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login, user registration" }
subdomain mulitsite on localhost in a subfolder I have a sudomain-based WPMU installation locally with xampp. My `vhosts` lists domains like follows: 127.0.0.1 mainDomain.com 127.0.0.1 siteA.mainDomain.com 127.0.0.1 siteB.mainDomain.com 127.0.0.1 siteA.com 127.0.0.1 siteB.com The `WordPress MU Domain Mapping` PlugIn maps "real-domains" on system-subdomains. To have a standard project structure, I would like to move my installation from the documentRoot to a subfolder. My question is, what do I need to do, to accomplish that and will it have any consequences for the compatibility between my local- and a live-system?
Multisite cannot be installed in a subdirectory of the document root currently. This will be possible in 3.5. See Multisite on Windows with wildcard subdomains for a guide how to manage subdomains automatically on Windows with XAMPP. You can move the plugin directory to another directory per `wp-config.php`. This is possible for themes too, but automatic theme upgrades will fail currently.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "multisite, domain mapping, local installation" }
Show content if parent page has children Using this piece of code you can show content depending if it's a child-page or not: <?php global $post; if ( is_page() && $post->post_parent ) : ?> This is a child-page. <?php else : ?> This is a parent-page. <?php endif; ?> But I would like to add one more statement, so that I could have different content if it's a parent-page that has a child, or a parent-page that hasn't. Would something like this below work? If yes, what would "XXX" be? <?php global $post; if ( is_page() && $post->post_parent ) : ?> This is a child-page. <?php elseif ( is_page() && XXX ) : ?> This is a parent-page (with one or more children) <?php else : ?> This is a parent page without children. <?php endif; ?> Thanks in advance!
I ended up using this code: <?php global $post; $children = get_pages( array( 'child_of' => $post->ID ) ); if ( is_page() && $post->post_parent ) : ?> This is a child-page. <?php elseif ( is_page() && count( $children ) > 0 ) : ?> This is a parent-page (with one or more children) <?php else : ?> This is a parent page without children. <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "php, conditional tags, child pages" }
get_all_category_ids for bookmark I was wondering how to create a list of categories name and ids for Wordpress Bookmarks such as `get_all_category_ids` for post. I tried using the `get_bookmarks`, but the category does not appear in it. **Update** : Based on advice from @Mridul-Aggarwal, I wrote code that might be useful: <?php $tautan=get_terms('link_category');//get links category object $html="<ul>\r\n";//Init /*Looping*/ foreach($tautan as $isi) { $nama=$isi->name; $id=$isi->term_taxonomy_id; $html.="\t<li>$id - $nama</li>"; }; $html.="</ul>\r\n"; /*Output*/ echo $html; ?>
what about `get_terms('link_category');`? Once you have the objects, you can use them to get whatever information you like.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "list, id, bookmark" }
Wordpress admin right sidebar isn't working I don't what happened but few times ago its working and now i don't what i did so it stops working, I want its quick fix, Currently when we're adding new post it looks like that screenshot : !enter image description here Column is already 2 and nothing changed when we use 1 column, I want its right sidebar.
I saw this with an older version of WordPress. I have not seen it with more recent updates. You fix is to update, honestly. This should be the least of your reasons to do so. Without updating, the only way I was able to sort it out was by editing the (if I remember correctly) `screen_layout_*` key values in the `*_usermeta` table using PhpMyAdmin, in my case. I should stress that that was a hack to get by until I updated. It isn't really a fix. _Caveat Emptor_. Also, update.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin" }
Load .txt file for login_message in wp-login.php How do I load the contents of a text file - or any other file, like .php - and use the test for the `login_message` hook that prints a message above the `#login` box in wp-login.php? _(BTW, this is in a child theme, if it makes a difference.)_ function custom_login_message() { $message = get_bloginfo('stylesheet_directory')."/tos.txt"; return $message; } add_filter('login_message', 'custom_login_message'); Right now, the function above prints out the URL of the file, not the text in the file, i.e.: !enter image description here
Use `locate_template()` if you want to use a file from your theme. `include()` or `require()` works too. Sample code, tested: add_filter( 'login_message', 'wpse_73619_include_login_message' ); function wpse_73619_include_login_message() { print '<pre>'; locate_template( 'style.css', TRUE ); print '</pre>'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, wp login form" }
How to show a full post, not just an excerpt I have a blog page where blog posts have an excerpt on with a continue reading link below. When the link is clicked the full post should appear/or should be diverted to. This isn't that case. The user is diverted to the post, however only the excerpt is displayed along with a continue reading link which doesn't activate anything. I have deactivated all plugins, I have also played around with the settings but can't find any triggers. Blog Page - < Post Page - <
You need to use `the_content` instead of `the_excerpt` when you display your 'single' post. If you would post your code, you might get a more detailed answer.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "posts, excerpt, blog" }
How to restrict Front-End Editor on a page? I am working on a site where the user can do everything from the front end. I am using the plugin from scribu called front-end editor. My problem, is that I have a dashboard page with all the options for the user and I do not want the user to be able to edit it. How do I restrict a page from being able to be edited by Front-End Editor. I have read the wiki on github for it here < and can't find anything about restricting pages. Only categories.
From the GitHub-Wiki ## The `'front_end_editor_disable'`-filter Use this filter if you want to completely disable the plugin for certain URLs. Callback arguments: `bool $disable`: The current state. Default: `false` You can use conditional tags: _Conditionals tags return`bool true/false`, which means, if you want to disable it on a page, simply use `is_page()`, as it returns `true` for pages..._ Disable FEE on pages, as a (mu)plugin. <?php /** Plugin Name: (#73660) Disable Front Page Editor on pages */ function wpse73660_disable_on_author_pages( $disable ) { return is_author(); } add_filter( 'front_end_editor_disable', 'wpse73660_disable_on_author_pages' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "plugins, front end" }
Show div based on custom meta value I've search all over for a solution to this but can't seem to find anything that does exactly what I want it to. Basically what I want to do is display a particular div within a post based on the value of a specific custom field. For example; If the value of the "featured" custom field is "1" then I want to be able to show a div within single.php for that particular post But if the value of the "featured" custom field is anything other than 1 then I don't want anything to appear. Does that makes sense?
Then you need a filter on `the_content`. function add_conditional_div($content) { global $post; $meta_field = get_post_meta($post->ID, 'your-field-name', true); if (1 === $meta_field) { $content .= '<div>whatever</div>'; } return $content; } The `1` value, of course, is whatever should match your meta_field. < < You could also edit your theme files directly or make a child theme. The latter is highly encouraged if you are editing a theme you didn't create.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "custom field" }
Add copies of the same text widget instance to multiple sidebars Note: This is not the popular question about how to create multiple instances of a widget. I have a text widget that I am using to display "business hours". This text needs to go in multiple sidebars and is likely to change often enough to be a nuisance to change it in multiple places. Is there a way to use the same instance of a text widget on more than one sidebar? Any alternatives that use tokens or some other kind of pointer would also be a solution.
A possible solution would be to enable shortcodes in the Text Widget. add_filter( 'widget_text', 'do_shortcode', 11 ); Then put the same shortcode (i.e.: "`[business_hours]`") in all text widgets, and all of them will display the same content. It's even possible to add some Conditionals Tags inside the shortcode definition to show different things according to the context where it is being displayed.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "widget text" }
Add script to footer - on post editor How do you add a script on the footer of the post editor ? I'm adding a meta box under the post editor and I need to include a javascript before the closing body tag (on the footer) How do I achieve this ? The script is not needed on the front-end just on that meta_box (just on the post editor page)
Hook into `'admin_footer-post-new.php'` and `'admin_footer-post.php'`, check the global variable `$post_type`: add_action( 'admin_footer-post-new.php', 'wpse_73692_script' ); add_action( 'admin_footer-post.php', 'wpse_73692_script' ); function wpse_73692_script() { if ( 'post' !== $GLOBALS['post_type'] ) return; ?> <script>alert( '<?php echo $GLOBALS['post_type'];?>' );</script> <?php }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "wp enqueue script, metabox, footer" }
Putting a Category of posts under a Page I have a website, say `mysite.com`, and there is a blog `mysite.com/blog`. When I post a new post under the `blog` category its appears like `mysite.com/newpost`. I want the posts under the `blog` category to be displayed under the `blog` tag like `mysite.com/blog/newpost`. How can I achieve this?
Set your permalinks to `/%category%/%postname%/`. This will set the category name in front of the post URL. If you want to use the **fixed** string `blog`, set the permalinks to `/blog/%postname%/`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories, pages, blog" }
Redirect based on log-in status per JavaScript I want to check if a user is logged in. If he is, I want to redirect him to page A, and if he isn’t to page B. The redirect should happen per JavaScript after a button has been clicked – so I need the status or the URL to be available in JavaScript. How can I get these data from WordPress into JavaScript?
To test if a user is logged in use `is_user_logged_in()`. To redirect a visitor use `wp_redirect($location, $status = 302)`. You can combine both: <?php $location = ' if ( is_user_logged_in() ) $location = admin_url( '/' ); wp_redirect( $location ); In JavaScript (sort of): add_action( 'wp_footer', 'wpse_73701_button' ); function wpse_73701_button() { $location = is_user_logged_in() ? admin_url( '/' ) : ' print "<button onclick='window.location.href=\"$location\"'>Click!</button>"; } You could also just create JavaScript variables and use them in your scripts: <script> var isLoggedIn = <?php print is_user_logged_in() ? 'true' : 'false'; ?>; var redirectTo = '<?php print is_user_logged_in() ? admin_url( '/' ) : ' ?>'; </script>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, javascript, redirect, login" }
W3 Total cache "empty all caches" and no stylesheets render I have the w3 Total cache plugin installed and so far its been great as I'm sure you will all agree, so thanks to the author for an amazing plugin. However, I used the "empty all caches" button on the general settings page and when the plugin is activated none of my stylesheets are loading so the page appears without any styling? I have to deactivate the plugin for the stylesheets to load. How can I reactivate W3 so that the stylesheets all render properly again?
W3 Total Cache combines .css files. If you do not want this to happen, deactivate the option on the page `wp-admin/admin.php?page=w3tc_minify`, section CSS `enable`. If this option is not available, try setting the `minify` settings on the main page of W3 Total Cache to `manual`. This Caching Plugin is awesome - but you have to tweak the settings quite a bit, if you are new to it mostly through trial and error, to get to the best result. Please be sure to check your page a few times after you finished your settings, and also check it in logged-out mode, I had a few problems with sites being processed right on their first call, but broken afterwards. A really tricky thing is the javascript-combining and minifying - if you are not 100% sure what you are doing, it can make your site a mess. But if you do - hello PageSpeed :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin w3 total cache, css" }
Exclude custom post type from list <?php $custom_post_types = get_post_types( array( '_builtin' => false, 'public' => true ), 'objects' ); foreach ( $custom_post_types as $custom_post_type ) { $custom_post_type->permalink = get_post_type_archive_link( $custom_post_type->label ); } echo '<ul>'; foreach ( $custom_post_types as $custom_post_type ) { echo '<li>'; echo '<a href="' . $custom_post_type->permalink . '">' . $custom_post_type->label . '</a>'; echo '</li>'; } echo '</ul>'; ?> I want to exclude products and sales CPT from the list. Can anyone help please? Also I want to display the list in ACS order.
<?php $custom_post_types = get_post_types( array( '_builtin' => false, 'public' => true ), 'objects' ); ksort( $custom_post_types, SORT_ASC ); echo '<ul>'; foreach ( $custom_post_types as $custom_post_type ) { $exclude = array( 'products', 'sales' ); if( TRUE === in_array( $custom_post_type->name, $exclude ) ) continue; $custom_post_type->permalink = get_post_type_archive_link( $custom_post_type->name ); echo '<li>'; echo '<a href="' . $custom_post_type->permalink . '">' . $custom_post_type->label . '</a>'; echo '</li>'; } echo '</ul>';
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "custom post types" }
How to remove tag base from permalinks How can I remove the tag base that WordPress creates by default in permalinks? Any reason why it would be there in the first place?
It's probably there to help visually and programmatically distinguish tag URLs from pages; I'm not sure, I'm not a core developer of WordPress. But < and < work well and do not make permanent changes to files or GUIDs, so they can be deactivated with no ill effects. Use the plugins as "regular" plugins, or as mu-plugins <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "tags" }
How do I programmatically generate a 404? How can I get something like this to work? // in a plugin / theme: // This imaginary function will make WordPress think that the // current request is a 404. // Ideally this function could be ran anywhere, but realistically it // will probably have to be before the template_redirect hook runs. generate_404_somehow(); // later... add_action('template_redirect', function() { // should be "true" var_dump(is_404()); }); Basically under certain conditions, I want to tell WordPress to show its 404 template (which I can hook into later if I want) instead of the template it's about to load (eg a page or archive). I know I could just do a `302` redirect to a non-existent page but that's very messy. I could also send a `404` HTTP header manually, but then I can't use WP's nice 404 page (I already have things that hook into `is_404()` that need to get fired at the right time).
function generate_404_somehow() { global $wp_query; $wp_query->is_404 = true; } add_action('wp','generate_404_somehow'); Of course, that will send all of you page to the 404 template. I don't know what the conditions are that this should fire or not fire. Or to be more cautious (see comments) ... function generate_404_somehow() { global $wp_query; $wp_query->set_404(); } add_action('wp','generate_404_somehow');
stackexchange-wordpress
{ "answer_score": 7, "question_score": 8, "tags": "redirect, 404 error" }
Get the category from an ID of a product? I have the `ID` from a product (`1345`) how can i get the category name of that specific product? I try $post_categories = wp_get_post_categories( $post->ID ); print_r( $post_categories ); but it outputs: Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) What those it means ? Thanks
Since the question is tagged woocommerce, i'm assuming that it's a product CPT created by woocommerce wordpress plugin. This answer doesn't apply if that's not the case. The products categories is not normal categories, they are a custom taxonomy created specifically for products which is just labeled as "Categories". You should go through the woocommerce documentation to find some function that would do this for you, if you don't find anything you can try an alternative solution. For that, first you should know the name of the taxonomy. You can copy it from inside the url in your browser when you visit categories edit screen in the backend. Then you can use `wp_get_post_terms` to get the terms.
stackexchange-wordpress
{ "answer_score": 12, "question_score": 11, "tags": "plugins, categories" }
Update exisiting site to 3.5 release candidate I have an existing site that I want to update to 3.5 now, because I want to see if my plugins and themes work in it. I don't want to wait for the full release (when I'll be able to automatically update), and I don't mind that 3.5 is still in release candidate state. I could just copy in all the files from 3.5, but I'm afraid that there might be some database changes too. I don't want to set up a separate test site. This is a small site, and it won't be the end of the world if something goes wrong. How can I update an existing site to a non-final version of Wordpress?
Use the **Beta Tester Plugin**. Be sure to set it to use **bleeding edge nightlies** , so that you get the pre-releases. Also: once a new major version is final-released, be sure to change the Plugin's settings back.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "plugin development, theme development, updates, upgrade" }
reason of splitting theme files to multiple files I can create my theme without splitting it into separate files. Why do theme developers split WordPress theme into a few single files like header.php sidebar.php and etc?
You need that for child themes. If you have a separate `header.php` a child theme can use its own `header.php` and override the parent theme’s file. Plus, `header.php` and `footer.php` are used in `wp-signup.php`. Another reason is readability: Putting all the code for a theme into just one file gets very messy very fast. A use case for a compact theme is testing and debugging: My Mini Theme uses just `index.php` and `comments.php` for output. Whenever a plugin doesn’t do what I expected I use that theme to be sure it is not a theme issue.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "php, theme development, themes, theme options" }
Extending a CPT by Created by another plugin I'm using WooCommerce for my store, and I need to be able to extend the Coupon post type... I need to add a selectable attribute of `membership_term` ... How do you extend a CPT created by another plugin? Is there an official hook that I'm not seeing to be able to modify an existing CPT?
I am not sure exactly what you are trying to 'extend', or how you want to extend it, but you can alter posts types with `add_post_type_support`, `remove_post_type_support`, and a few other functions. You can add metaboxes to the post type with `add_meta_box` setting the `$post_type` argument to the name used to register your post type. (Examples are on the Codex page) Unless the original plugin provided a hook you won't be able to directly alter its metaboxes but you can use `remove_meta_box` to remove existing boxes and then add back a near clone of the metabox with your changes. You will have to hook into `save_post` or [`admin_action_{$_REQUEST[action]}`]( to save any additional fields you create.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, metabox, plugins" }
Disable block with taxonomies at post page I am developing an events manager for Wordpress. I have post_type = 'event' and taxonomy 'event_place' And I want delete block with taxonomy select in post page, because user can do it at custom metabox. !enter image description here
Use `remove_meta_box` remove_meta_box( 'categorydiv', 'post-type-name', 'side' ); And hook it to 'admin_menu' as in the Codex. function my_remove_cat_box() { remove_meta_box( 'categorydiv', 'post-type-name', 'side' ); } add_action( 'admin_menu', 'my_remove_meta_boxes' ); I am guessing a little at the first parameter--'categorydiv'--, but that is what it looks like based on your screen shot.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, posts, custom taxonomy" }
How to check the array values, what WP_Query has brought to me? I have two questions in a row: * How to check the array values, what `WP_Query` has brought to me? * If I get 10 posts in cat=3, then I want to get only 5 from them, and then want to echo them individually wherever I want them to print. It may be like: ------------------- | 1 | 2 | ------------------- | 3 | 4 | ------------------- | 5 | ------------------- But I don't have any idea on both of the problems.
Assuming you start with: $custom_query_args = array( 'cat' => 10, 'post_per_page' => 5 ); $custom_query = new WP_Query($custom_query_args); Then to answer your first question, you can see what is returned (for development/debugging) via: var_dump( $custom_query ); To output your query as a normal loop, you simply need to call a custom loop, using the `have_posts()` and `the_post()` member functions of the Query class: // Start loop if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); // Loop output goes here // End loop endwhile; endif; // Restore $post data to the default query wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, query" }
Custom Taxonomy Images with Advanced Custom Fields I've created a custom Taxonomy for a Custom Post Type, and created five or so terms within the taxonomy. I've created a single image upload and assigned it to the custom taxonomy, and uploaded images for each term. I can't for the life of me figure out how to get the image to display. I've var_dumped the term but there's nothing in there about the image? Any help much appreciated! WP version: 3.4.2 ACF version: 3.5.3.1
As per the plugin documentation: > The second parameter needed is a string in the format “$type_$id”. // get value from a taxonomy (taxonomy = "category", id = 3) $value = get_field('field_name', 'category_3'); // get value from a taxonomy (taxonomy = "events", id = 76) $value = get_field('field_name', 'events_76');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom taxonomy, images, advanced custom fields" }
How to dynamically save a selected option from page "Templates" selectbox? When I select a template for a page from the "Templates" selectbox, the selected item gets “value=selected” only after I hit save draft/publish/update. `<option value='template-gallery.php' selected='selected'>Gallery</option>` How can the option receive the value “selected” without the need of save/publish/update hit button? (like on widgets page: they get saved without page refresh) Thank you!
This would have to be fully coded and tested, but I think the roadmap is: ### Deregister the Default Meta Box and Make a Custom One @MikeSchinkel answer to this question is very detailed and thoughtful: Adding Page Attributes Metabox and Page Templates to the Posts Edit Page? In that case, it is for _duplicating_ the Pages Template Meta Box into _Posts_. This other Q&A ( How To Change Custom Taxonomy To Radio Buttons ) provides an example of _replacing_ the Taxonomies Meta Box. ### Add Ajax to the Custom Templates Meta Box In this answer, there's an example of custom meta box that runs an Ajax call, that in turn makes a database query to modify an attachment parent. To do the Page Template live switch, it would be a matter of modifying the table `wp_postmeta` where the current template value is stored. The `meta_key` name is `_wp_page_template` and its value the template file name. !results of query wp_postmeta _wp_page_template
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "pages, templates, page template, select" }
Filter front page posts by category I have three categories (news, pics, vids), but I have all of them showing up on my front page. I would just like the front page to have the news category (and possibly uncategorized category) to show. What is the best way to do this? Plugin? Or a piece of code on the front page?
Try adding this code to `functions.php` file: add_action('pre_get_posts', 'ad_filter_categories'); function ad_filter_categories($query) { if ($query->is_main_query() && is_home()) { $query->set('category_name','news, uncategorized'); } } `category_name` is the slug or the nicename of the category. Add a comma separated list of the categories you wish to include.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "categories, frontpage" }
How to configure nginx for wordpress I'm having a working nginx, php-fpm and other php packages and mysql. I've extracted wordpress-3.4.2.zip in /usr/local/nginx/html/blog. When I visit localhost/blog I get "500 internal server error". Is there any special configuration that needs to be done for nginx to make wordpress work?
Provided info by you is SO huge... so i can only advice. 1. run nginx - it works? goto step 2 2. run nginx with php, see info.php with phpinfo() insie? goto step 3. 3. run nginx with php and global host rewrite to this index script. It works ? go to step 4. 4. run nginx with php and anabled error reporting (logs/display anything). do typo in script. see error? good. now you can TEST whats problem you have with php. Generaly this is nginx issue not the wordpress. please back to us whan you willl do all these steps. 3) Script code and sample Nginx Configs <?php var_dump($_SERVER['REQUEST_URI']); ?> 4) PHP bugly code. <?php vardump($_SERVER['REQUEST_URI']);?> NGINX (change error log location if you want.) fastcgi_param PHP_VALUE "error_log=/var/log/nginx/host1.php.error.log";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "nginx" }
queries inside of a class I'm building a plugin and I'm quite new to wordpress I have a class what has couple of methods what should execute database queries. The class look as it follows class MyClass{ private $wpdb; function __construct(){ global $wpdb; } function query(){ $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->wp_competitors ( id, field_key, field_value ) VALUES ( %d, %s, %s )",1, $field_key, $field_value) ); } } I would like to be able to use inside of my class wordpress native database class, how to do this?
class MyClass{ function __construct(){ global $wpdb; $this->db = $wpdb; } function query(){ return $this->db->query( $this->db->prepare("INSERT INTO {$this->db->wp_competitors} (id, ield_key, field_value) VALUES ( %d, %s, %s )", 1, $field_key, $field_value) ); } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "php, wpdb" }
How to Create a Directory in a Plugin Folder? I am creating a plugin in WordPress Version 3.4.2. When the administrator submits a form, a new folder is created inside my plugin directory and a file saved in this new folder. But it gives me the following error: error : The file has not been created $dir = plugins_url()."/folder-name/; The above code returns the following path: mkdir($dir, 0777, true);
Do not use the plugin directory to store new files. * During an update the plugin directory will be erased by WordPress. And all files in it too. * The plugin directory might be read-only in some setups (I do that always). Use the regular uploads directory for that. And `0777` is never a good idea. Write access for everyone is probably not what your users want.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "plugins, plugin development, php" }
How to not show tags if the post doesn't have any? I currently have the following trying to avoid showing tags (the icon in this case) when there aren't any, but the icon continues to show up. Any thoughts? <?php if ( is_singular() && function_exists('the_tags') ) : ?> <p><i class="icon-tags"></i><?php the_tags('', ', ', ' '); ?></p> <?php endif; ?>
Get a **string** value for the tags and print it only if there _are_ tags: $tags = get_the_tag_list('', ', ', ' '); if ( "" !== trim( $tags ) ) { echo "<p><i class='icon-tags'></i>$tags</p>"; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "tags" }
Wordpress custom permalinks not working on OS X localhost When changing premalinks, none of the pages and links are not working except home page :( !enter image description here Result are shown below. Thanks in advance. !enter image description here
This is really a server question and not specific to WordPress. Be sure `mod_rewrite` is enabled in `httpd.conf` Apache on your version of OS X. (Google that with your version of OS X.) Restart Apache after making changes to httpd.conf. You may also need to add a blank .htaccess file in the /Users/yourusername/Sites folder so the file has the correct permissions and so WordPress can write to it from the Settings >> Permalinks screen in admin. And to do that, you will need to add the .htaccess file in Terminal, as OS X hides unix "invisible" files - files with a leading . - in the finder.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "wp admin, options, localhost" }
Sorting Woocommerce products with numeric titles Just started playing around with Woocommerce, ran into a problem. I have a bunch of items (100+) and all of them only have a number as product title, 1,2,3 etc. The problem is that Woocommerce outputs the products like this: 1,11,12,13,14,15,16,17,18,19,2,20 – and so forth. How can I make it output correctly?
You'll either have to sort/order your products manually or create a custom sort order within WooCommerce. For that take a look at the WooCommerce docs and this snippet for doing just that. In this case you're also going to have to do a bit of MySQL manipulation as well so that you're sorting the _numbers_ numerically. See this post on stackoverflow for an example. **NOTE:** You may have some performance issues with the MySQl as a result.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "loop, order, plugins" }
Do WordPress Core Filenames Work as Hooks? This is in reference to another answer here on wordpress.stackexchange. The answerer used the filename as the hook to enqueue scripts and styles to certain pages. add_action( 'admin_print_scripts-post-new.php', 'portfolio_admin_script', 11 ); add_action( 'admin_print_scripts-post.php', 'portfolio_admin_script', 11 );
The short answer is 'yes'. Taken from this article the suffix of those 'screen specific hooks' is given by: * For custom admin pages added via `add_menu_page()` \- including settings pages - (and related functions) it is the screen ID (the value returned by `add_menu_page()`) * For the admin page listing posts of any post type, it is `edit.php` * On the ‘add new’ page of any post type, it is `post-new.php` * On the edit page of any post type, it is `post.php` * For taxonomy pages it is `edit-tags.php` You may find this plug-in useful, developed by @Kaiser, based on the article linked to above.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "hooks, filesystem" }
Enclose title within a div? I'm using this code to display a page within my front page. I would like to learn how to add a div / spacer to isolate the page title... If I try to add a div class within the php code then it throws errors. **Question: How can I add a div to the title within this bit of code?** <div class="frontpage"> <?php $page_id = 2945; $page_data = get_page( $page_id ); echo '<h3>'. $page_data->post_title .'</h3>'; //enclose the title within a div/spacer??? echo apply_filters('the_content', $page_data->post_content); ?> Thanks
Try to change heading from echo '<h3>'. $page_data->post_title .'</h3>'; like echo '<div class="class-name">'. $page_data->post_title .'</div>';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "title, post class" }
How To Get Custom Post Type Category Title I have a CPT called campsites and in there I have different categories ie. derbyshire, staffordshire, nottinghamshire etc. What I want to do is that when you click on a category eg. derbyshire, ideally I'd like it to say at the top of the page Campsites in derbyshire. Please help.
From what I understand, you just need to use this in your template as it sounds like you will be using an archive page for a given CPT. <h1><?php post_type_archive_title(); ?></h1> I've not been able to test this but you can find more info about the options on this Wordpress Codex page. < There are other solutions based on how your page is going to be displayed so feel free to give more info if this doesn't work. Based on your comment, you may be able to use a simple tag like this... <h1><?php echo single_cat_title(); ?></h1> If it still won't play you may need to go slightly more in depth and I'll need to do that from my main computer later as I have done this same thing recently.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types" }
Page header menu links change I am trying to find out where the header menu links on my WP is located so that i can change the URL of the page. the link is: < and i need to change it to: < However, i do not see anywhere in the menus that i have to change that link. I even looked into the mySQL database **wp_posts** and tried changing all references to 11 to 36 but it still comes up 11!??! Where could i be overlooking it? The appearance Menus page: !header menu And the header page itself: !header page And the header code: !navcode
Note that you're using a _Custom_ Nav Menu, meaning that the contents of the menu can be _customized_. The easiest solution is simply to: * _remove_ the current "Our Doctors" page from the menu * _add_ your desired page to the menu * _edit_ the menu item to change the displayed title to "Our Doctors" * save the menu
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, permalinks, pages, headers, custom header" }
Fetch array with $wpdb I am trying to convert this code to use the $wpdb. $data = array(); $query = "SELECT * FROM videos"; $query_exec = mysql_query($query) or die(); while($row = mysql_fetch_array($query_exec)) { if ( $row['video'] == " ) { $data[$row['id']] = end(explode(' $row['video'])); } else { $data[$row['id']] = end(explode('?v=', $row['video'])); } } So I did: $query = $wpdb->get_results("SELECT * FROM videos"); But how can I fetch the array? Thank you in advance for the help.
`wpdb`'s `get_results` method takes an optional second argument that lets you specify how the data is returned. The default return is an object. But you can also set it to... > OBJECT - result will be output as a numerically indexed array of row objects. > > OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded). > > ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys. > > ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays. (from the codex) You probably want `ARRAY_A`. <?php $query = $wpdb->get_results("SELECT * FROM videos", ARRAY_A); Unfortunately, `wpdb` doesn't allow you to "stream in" results like you're doing, so you'll need to use a foreach loop. <?php foreach($query as $row) { // do stuff with $row here. }
stackexchange-wordpress
{ "answer_score": 30, "question_score": 13, "tags": "wpdb, array" }
How can I sort posts ascending by post title for a specific post type, but on a category archive template? How can I sort posts ascending by post title for a specific post type, but on a category archive template? My schema involves a "video" custom post type and multiple subcategories of the aforementioned post type. I am using the Custom Content Type Manager plugin. How can I implement this?
You can use `pre_get_posts` to hook in and change the query. The argument passed to `pre_get_posts` is the query object. It fires for every query, so you need to check some things first. Quick example (not-tested) -- change the order on only the video type's post type archive page. <?php add_action('pre_get_posts', 'wpse73991_change_order'); function wpse73991_change_order($q) { if( is_admin() || // no admin area mods !$q->is_main_query() || // make sure we're modifying the main loop !$q->is_post_type_archive('videos') // is this the video archive? (you might need to change this) ) return; // bail, we're not where we want to be. // change the order $q->set('order', 'title'); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, categories, sort, template hierarchy" }
Remove the deleted user comment ## Problem I have a user based site, so when user **deletes** his profile somehow his/her comments stay visible. There is no name and blank avatar with the comment. Is there any way to delete the comments of a user if the user deletes his/her profile and how? Is there a function of somehow? This really is a strange problem.
+1 @toscho 's comment. This will break nested comment / conversation in comment. You should disable nested comments in the Settings. Try this code. Note that this is not tested add_action( 'delete_user', 'my_delete_user'); function my_delete_user($user_id) { $user = get_user_by('id', $user_id); // delete comment with that user email $comments = get_comments('author_email='.$user->user_email); foreach($comments as $comment) : wp_delete_comment($comment->$comment_id, true); endforeach; // delete comment with that user id $comments = get_comments('user_id='.$user_id); foreach($comments as $comment) : wp_delete_comment($comment->$comment_id, true); endforeach; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, users, customization" }
Authors' Links on Homepage Not Going to Author Post Pages This problem only occurs with the articles/blog posts on the homepage of the site, readbuzz.com. On the homepage of the site, the author's name is supposed to link to that particular author's post page, where all the blog posts the author posted on the website will show up. Instead, each name that shows up links to the homepage. Yet, when you click and go into any of the posts on the homepage, then checked the author's link, it takes you directly to that author's post page. I know I need to include this function, but can't seem to find the place where I need to edit this: link **UPDATE: The code below is the correct code, in several different PHP files. Currently need to know how to write it using the the_author_posts_link();** <p class="postAuthor">By <a href="<?php the_author_meta('user_url'); ?>"><?php the_author(); ?></a></p>
> The code below is the correct code, in several different PHP files. Currently need to know how to write it using the the_author_posts_link(); > > > <p class="postAuthor">By <a href="<?php the_author_meta('user_url'); ?>"><?php the_author(); ?></a></p> > Just replace this: <a href="<?php the_author_meta('user_url'); ?>"><?php the_author(); ?></a> With this: <?php the_author_posts_link(); ?> Alternately, you could use this: <a href="<?php echo get_author_posts_url(get_the_author_meta( 'ID' )); ?>"><?php the_author(); ?></a> Codex references: * `the_author_posts_link()` * `get_author_posts_url()` * `get_the_author_meta()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, links, author" }
How can I use get header from within my plugin? I'm writing a plugin to do some specific business logic - edit records for authenticated users, etc. Rather than having the overhead of a form processing plugin that uses stuff in template tags. I've created a rewrite do redirect like: /mylisting/909 ->/wp-content/themes/myplugin/edit.php?id=909 Which seems to make sense as I'm keeping the very specific logic to an individual plugin. The problem is, I want to use my theme within my plugins files as they'll be output in the site's frontend and as such I want them to have the same look and feel. So I've tried get_header(); include('../mytheme/header.php') As well as including wp-load.php ...None of which work (I get fatal errors) Any help?
> I've created a rewrite do redirect like: > > > /mylisting/909 ->/wp-content/themes/myplugin/edit.php?id=909 > > > Which seems to make sense as I'm keeping the very specific logic to an individual plugin. There is a better way: Create an endpoint, use your code in a callback handler for the new URL. You get the whole theme environment for free here: `get_header()`, sidebars, menus etc. Do not forget to call `exit;` at the end of your endpoint, othrwise WordPress will use the theme files again. :) The plugin URI is never a good address to edit or create content: It might be on another domain where the cookies are available, and no user is ever logged in.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, themes, endpoints" }
get_terms on save_post hook Usually, if I want to check for some attribute of the post I'm about to publish, I will check like this: $post_title = $_POST['post_title']; post_title is the name of the title field in the edit window. I thought I'd apply the same logic to the taxonomy meta box. $formats = $_POST['tax_input[formats][]']; Essentially, I'm trying to check if a specific taxonomy term is being selected when I publish a post.
You're on the right track. When you do something like this in a form.. <input name="tax_input[formats][]" /> You create levels in the `$_POST` array. So you'd get the formats array like this... <?php $formats = $_POST['tax_input']['formats']; Full example... <?php add_action('save_post', 'wpse74017_save'); function wpse74017_save($post_id) { // check nonces and capabilities here. // use a ternary statement to make sure the input is actually set // remember that `save_post` fires on every post save (any post type). $formats = isset($_POST['tax_input']['formats']) ? $_POST['tax_input']['formats'] : array(); // do stuff with $formats }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "publish, save post, terms" }
How to List Events by Year and Month Using Advanced Custom Fields? I have a custom post type "Kalender_item" with a custom Date Field (YYMMDD). I want to list all the posts on a page sorted by Year and Month. For example: * November 2012 (all events that occure in November 2012) * December 2012 (all events that occure in December 2012) And so on... I have succeeded in ordering them like so $kalenderItems=query_posts('post_type=kalender_item&post_status=publish&meta_key=kalender_item_datum&orderby=meta_value'); This gives me all my posts in the correct order. Now I want to group them by Month Year and display the Month Year as a title for each group. How to group my results by year and month?
This should get you started: <?php $the_query = new WP_Query( array( 'post_type' => 'kalender_item', 'post_status' => 'publish', 'meta_key' => 'kalender_item_datum', 'orderby' => 'meta_value' ) ); # This will hold what group we're in $current_header = ''; # The Loop while ( $the_query->have_posts() ) : $the_query->the_post(); # get the datum for this post $temp_date = get_post_meta( get_the_ID(), 'kalender_item_datum', true ); # If they aren't the same, we'll start a new group, which for now # just means setting a new heading if ( $temp_date != $current_header ) { $current_header = $temp_date; echo "<h2>$current_header</h2>"; } # ... do normal loop stuff here endwhile; ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "query, date time, advanced custom fields" }
WPeC - Adding conditional logic to purchases I need to add conditional logic to purchases. ie – **_item a** included for free with the purchase of **item b** or **item a** can be purchased individually for x amount_. Does anyone know if this functionality can be achieved through settings on the backend of WPeC. Thanks Cam
There isn't an out of the box solution for this in WP e-commerce. But if your products are downloads you could simply add the file as a variation.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "theme development, plugin wp e commerce" }
Getting only direct child pages in WordPress with get_pages I am trying to fetch all direct children of a page. But I am getting all children and grand children as well. Any ideas? **PHP Source:** $args = array( 'child_of' => $post->ID, 'parent ' => $post->ID, 'hierarchical' => 0, 'sort_column' => 'menu_order', 'sort_order' => 'asc' ); $mypages = get_pages( $args ); foreach( $mypages as $post ) { $post_tempalte = the_page_template_part(); get_template_part( 'content' , $post_tempalte ); } My `$args` should be correct according to the documentation, but it's totally ignoring `parent` and `hierarchical`. **My page structure is as follows:** > Parent > -Child 1 > -Child 2 > \--Child 1 to child 2 > \--Child 2 to child 2 > -Child 3 And I only want to get `child 1`, `child 2` and `child 3`.
Please check the parameter 'parent'. It seems there is a space after the name.
stackexchange-wordpress
{ "answer_score": 13, "question_score": 26, "tags": "php, loop, pages, page template" }
Custom page sidebar using Template dropdown box i am wondering how i go about making a Template for some of my pages to use a different sidebar? I have created the widget like this: register_sidebar(array( 'id' => 'ourPat-sidebar', 'name' => 'ourPat Sidebar', 'before_widget' => '<div class="widget %2$s" id="%1$s">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>' )); In side my Functions.php code. Then i go into my Widget panel and its displayed just fine. Then i proceed to add text to it in order to form the sidebar html. !widget menu However, when i go to my Page menu and create a new page, i do not have the choice to use the custom widget code? !theme So i must be doing something incorrect since its not in there. To recap, i'm just looking for a way for different pages of mine to use a different sidebar using a custom widget i made.
In order to accomplish this you will need to also create a separate page template to use. You may need to double check your template head information. Example: <?php /* * Template Name: Your Template name */ ?> This has to be put at the top of the page template. Then within the custom page template you will need to call the custom sidebar that you have. You will need to put this in the template where you want your sidebar to go: <?php if ! dynamic_sidebar( 'ourPat Sidebar' ) ) : ?> You need to add widgets for items to show in this area. To add for this area add widgets to "ourPat Sidebar". <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, widgets, page template, sidebar, register sidebar" }
How to specify expiration of cacheable resources? I'm trying to speed up a wordpress site -- this site: < I'm following the observations here: < The first item says: "The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources:" How do I specify expirations for those things? (I'm not very technically-minded, and likely won't know relevant terminology -- really appreciate baby-steps explanation if possible :)
Keeping the answer within the wordpress realm, your **best bet is to installW3TC** and use that plugin to optimize your speed. Even with the default settings you'd already be gaining a lot. If you want to delve further you can keep tweaking the settings within the plugin. The next step to take would be setting up (with the help of the plugin) Cloudflare. I would not worry about speed optimization outside of anything this plugin can do. The only exception to this rule: if you are on a VPS or dedicated server you can further speed it up by employing APC and Varnish.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "cache" }
What is the proper way to get logged in user id in a plugin? I need to get logged in user id inside my plugin. Is this the proper way? $root = dirname(dirname(dirname(dirname(__FILE__)))); if (file_exists($root.'/wp-load.php')) { require_once($root.'/wp-load.php'); } $user_id = get_current_user_id(); Otto saying that we shouldn't load wp-load.php file since we have no idea where wp-load.php file located and it doubles the server load. So I'm really confused. And one more question.. Check this Rarst's Image According to that image wp-load.php loaded before all the plugins. So why all plugin authors include that file again?
If you're inside a plugin, WordPress is already loaded. You don't need to load it yourself. Inside whatever function needs the user ID, you need to do two things: 1. Globalize the user data variable 2. Populate the user data variable Here's some pseudocode: function some_function_that_needs_user_info() { global $current_user; get_currentuserinfo(); // Now reference $current_user->ID in your code. }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, users" }
Auto resize images after adding a new size I have added a new (small) image size to the theme we develop: `add_image_size('small', 160, 91, TRUE);` How to automatically generate these small images (exactly of the specified size) for every image uploaded in the past?
WordPress doesn't regenerate the newly registered size, only applies it to future uploads. You'll have to use something like the Regenerate Thumbnails plugin or one of the similar ones available at WordPress.org.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "images" }
How to wrap "Read More" link in a DIV tag? Can someone tell me how to wrap the Read More anchor (that displays after an excerpt) with DIV tags using `get_the_content('Read More')`?
Put a filter on `the_content_more_link`. Untested but... function wrap_more_link($more) { return '<div>'.$more.'</div>'; } add_filter('the_content_more_link','wrap_more_link');
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "excerpt, read more" }
Preferred Wordpress video format? I'm developing a Wordpress blog for a client who needs to embed their own video files. Flash video was our format of choice until recently, but is there a preferred format for Wordpress? One that easily integrates?
The Codex lists several core-supported oEmbed sites (including a few being added in 3.5): * YouTube (only public videos and playlists - "unlisted" and "private" videos will not embed) * Vimeo (note older versions of WP have issues with https embeds, just remove the s from the https to fix) * DailyMotion * blip.tv * Flickr (both videos and images) * Viddler * Hulu * Qik * evision3 * Scribd * Photobucket * PollDaddy * WordPress.tv (only [ VideoPress]-type videos for the time being) * SmugMug (WordPress 3.0+) * FunnyOrDie.com (WordPress 3.0+) * Twitter (WordPress 3.4+) * Instagram (WordPress 3.5+) * SlideShare (WordPress 3.5+) * SoundCloud (WordPress 3.5+)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "video player" }
What is the Plural of WordPress? I mean, for what I remember of my english classes it should be `WordPress'`, or not? Would this be a Meta Question? Or a English Language & Usage one? **[update]** What I ended up writing (in an email) before Comments and Answers was > ...deal with a couple of WordPress' projects... **[update]** Well, it ended up being an _Engrish_ Fail. Thanks, Johannes, for opening the question at English Language & Usage. Toscho's answer also prompted me to open another at Spanish Language and Usage, but for a person's name. (oh, my, is this apostrophe correct?) _In spanish, it would be "Los WordPress"._
WordPress is a singular without plural. A second instance would be a fork that could not use the same name, because the name _WordPress_ is a trademark of the WordPress Foundation. Like _Jesus_ , just more rules. _If_ WordPress had a plural it would be WordPresses, like in _mess_ or _mistress_. But the prerequisite for that would be that WordPress becomes either a _physical object_ or _self-aware_ (and able to create self-aware copies). I will update my answer on the day that happens.
stackexchange-wordpress
{ "answer_score": 19, "question_score": 15, "tags": "wordpress.org" }
WP admin bar disappeared The admin bar suddenly disappeared from the front end side of my site. It is present and works alright at the backend. I thought it could be due to some plugin so I deactivated them one by one and checked . Now all the plugins are deactivated and the admin bar is still missing...My theme does have the `wp_footer()` in footer.php. What is it that I am missing?
**Might be one of 3 things (since you verified a wp_footer)** 1. you set it to not show in your user profile 2. a plugin you installed has a Confliction with it 3. you created a php / js code which produces errors in your wp_footer **Course of action:** 1\. Check you personal user profile backend to see you haven't turned it off 1\. turn off all plugin (rename plugins folder temporarily) 2\. Activate wp-config errors display on (and check for errors) _\- Response to this & fix errors._ Hope this helps get to the root of the problem... Basiclly these are steps to be taken before asking a question so we could have the additional information incase this does not solve you issuse. Best of luck, Sagive
stackexchange-wordpress
{ "answer_score": 9, "question_score": 4, "tags": "admin bar" }
How to set up conditionals in page templates? I have created custom template page like this with a custom query on page showing only details fetch from my custom table not any post. /* Template Name:product */ <?php get_header(); ?> <?php $data = $wpdb->get_results("myquery Here"); foreach($data as $row) { product Name: $row->p_name; prod price: $row->p_price; ?> <a href="">VIEW PRODUCT</a> <?php } ?> <?php get_footer();?> I need help about when we click on "VIEW PRODUCT" then how can I redirect to next view_detail page? For that can I create another *view_detail.php* page? What should I write on `href=""` with passing `product_id`, which I get on view_detail.php.
<?php /* Template Name:product */ get_header(); // check if product_id is not set or is empty string if( !isset($_GET['product_id']) || '' == $_GET['product_id'] ) { // if so, run your query and display data $data = $wpdb->get_results("myquery Here"); foreach($data as $row) { echo '<div>'; echo '<p>Name:' . $row->p_name . '</p>'; echo '<p>Price:' . $row->p_price. '</p>'; // pass ID using GET echo '<p><a href="?product_id=' . $row->p_id . '">VIEW PRODUCT</a></p>'; echo '</div>'; } } else { // product_id is set and is not empty require('/path/to/view_detail.php'); } get_footer();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, page template" }
Making a form for user to add new custom post with custom taxonomies and custom fields !enter image description here I want to ask that is there a way display all my custom taxonomies in a drop down menu with checkboxes so when the user check any taxonomy it will be slected and when the user click the submit button .the new post will be created with selected custom taxonomy. i know how to insert it in new post but i WANT TO KNOW ABOUT THE DROPDOWN WITH CHECKBOXES IN THE RED BOX
To list the options for a custom taxonomy you need to query the taxonomy terms. To do that you use `get_terms()` < // We are assuming color is the name of the taxonomy $colors = get_terms( 'color', array( 'orderby' => 'name', 'hide_empty' => 0 )); // Now loop through the colors and spit out the checkbox // with the name of the color as well as the value of the term_id foreach($colors as $color){ .... On the server side for handling the submission (once you get the form correct) you can use `wp_set_post_terms()` <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, posts, custom taxonomy, custom field, forms" }
How to get the group_id from the "groups_join_group" action in buddypress I want to get the GROUP_creator_id when an user joins any GROUP. So if I got the `group_id` after immediately performing the the `groups_join_group` action by `add_action()` method.
`$group_id` is the first argument passed to `groups_join_group` action hook function, the second argument is `$user_id`. You can use these data to obtain group `creator_id` like: add_action('groups_join_group', 'my_groups_join_group_action', 10, 2); function my_groups_join_group_action($group_id, $user_id) { // use $group_id and $user_id here: $group = groups_get_group( array( 'group_id' => $group_id ) ); $creator_id = $group->creator_id; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "buddypress, actions" }
How the widget can be run by shortcode I have my own widget, that uses WP_Widget class, and executes its code inside function in this class. Is there any ways to run this widget using shortcode inside post? This is how my widget structure looks like: add_action( 'widgets_init', 'register_my_widget' ); function register_my_widget() {} class My_Widget extends WP_Widget () { function My_Widget() {} function widget() {} function update() {} function form() {} } How can I add the shortcode for executing this widget?
I think you are out of luck as wordpress core doesn't have this kind of functionality. Quick googling shows that there are plugins to do that like this one < but if you have programming skills you should probably write a shortcode handler with/instead of the widget.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "widgets, shortcode" }
Set a hard-coded page-template (post-type-archive) as home/front-page of my wordpress blog? under Settings->Reading I can set which page should appear immediately when visiting my site as "home-page". In my case I want the archive of my custom-post-type named "events" as home/front-page of my site. So I have a hardcoded item in my navigation that says "Events" that links to /events and uses my custom-post-template to loop through my custom-post-type. How could I (and what is the best way) set this archive as the automatic home/front-page of my site? I want to avoid unnessecary routing on my page. So when calling "www.mypage.com" I want the archive to appear immedeately. Any ideas on that? Preferrably even as setting in my "Settings->Reading" section in the backend. Thank you in advance. Matt
I would do this: Create template and include events archive file <?php /* Template Name: Index Events */ get_template_part( 'category-events' ); // Archive for Events (category-events.php) ?> Then create page using this template and finally select this page in Settings -> Reading
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, archives, options, homepage" }
SQL query - get ids - Advanced Custom Fields / WPeC I need to query the database on add_action( 'init', '...') to find post ids with the field 'product_discount_option' set to true. I know at least one of my product posts have the field 'product_discount_option' set to true. However when i run the SQL query below and var_dump it outputs an empty array , array(0) { } .. add_action( 'init', 'retrieve_product_ids'); function retrieve_product_ids(){ global $wpsc_cart, $wpdb; $product_ids = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM `".WPSC_TABLE_META."` WHERE `meta_key` = 'product_discount_option' AND meta_value = true" ) ); var_dump($product_ids); } The field 'product_discount_option' has been setup using the Advanced Custom Fields Plugin. The posts are WPeC custom post types, post_type = 'wpsc-product'. I'm new to SQL queries, sorry if i've missed anything in the question. thanks Cam
Thanks for your help s_ha_dum, I had a look at the table structure using phpMyAdmin, ACF Plugin saves fields to the postmeta table, so sb_wpsc_meta needed to be changed to sb_postmeta. also needed to change what was being SELECT to post_id aswell as the meta_value to 1. final query; "SELECT post_id FROM sb_postmeta WHERE `meta_key` = 'product_discount_option' AND meta_value = 1"
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, mysql, plugin wp e commerce, advanced custom fields" }
Reversing the order of items in a category rss feed? Is there an easy way to reverse the default item order of a category rss feed? Default: Last posted item first Wanted: First posted item first No plugins please, plain wp api function calls (such as add_action or add_filter) will do!
You can simply reorder your RSS Feed via the GET parameter `?order=ASC` or `?order=DESC` after your FEED url!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, rss, feed" }
Check if specific username is logged in How can you check if specific username is logged in?
`wp_get_current_user` then compare the object that's returned `user_login` proprety with the specific username you'd like to check against. <?php add_action('admin_init', 'wpse74389_check_username'); function wpse74389_check_username() { $user = wp_get_current_user(); if($user && isset($user->user_login) && 'username_to_check' == $user->user_login) { // do stuff } }
stackexchange-wordpress
{ "answer_score": 12, "question_score": 4, "tags": "users, user access" }
Is there an existing capability to allow editing of only pre-existing pages? If not, a good way to implement this? I'm working on a setup for which I need general users to be able to edit a specific list of pages, but not create any new ones. Looking through the Codex, I don't see anything that will come close to this desired functionality, but I thought I might be looking through it. Failing a pre-set, I started looking into Advanced Access Manager, but it was not immediately obvious to me if it would do what I need. Anyone with experience with this plugin have any idea where to begin?
In WordPress 3.5 there will be a new capability `create_posts`. You could create a new user role or change the role `editor` and remove that capability for this role.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "user access" }
How to link a Custom Post Type submenu to a Nextgen Gallery page? I've created a custom posts top level menu item but I would like to have a submenu under that linking to the Add Gallery page of Nextgen, as the client wants all their functionality bundled up under one top level menu item. So far I'm doing : add_submenu_page( 'edit.php?post_type=events', 'Add Gallery', 'Add Gallery', 'administrator', 'nggallery-add-gallery', 'event_add_gallery' ); But the link looks like: Is there any way to achieve this?
It would go like this _(note the absence of thefunction parameter \- and also the capability instead of a role)_. add_action( 'admin_menu', 'wpse_74421_menu_admin' ); function wpse_74421_menu_admin() { add_submenu_page( 'edit.php?post_type=events', 'Add Gallery', 'Add Gallery', 'delete_plugins', 'admin.php?page=nggallery-add-gallery' ); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "add submenu page" }
How to Setup a CDN for All Content? I know it's possible to setup a CDN with W3 Total Cache for cached content. However, how would I setup a CDN with WordPress to initially upload all media content (images, videos, files, etc.) directly to the CDN instead of my web host/local install. I'd like to completely bypass uploading content to my hosting account and simply host it via CDN. For example: if I uploaded an image via WordPress, I'd like it to automatically be sent to the CDN.
To totally bypass WP, just use the CDN native interface or a utility like cyberduck to upload you files directly to the CDN and embed the file from the "From URL" tab at the add media thing. This can work with files and video but will be problematic with images as WP process images to create thumbnails and gather EXIF and location information if they have. If you need any of this then you can't totally bypass WP unless you are willing to generate this info by some other way.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "cdn" }
Exclude categories from homepage but not from sidebar I would like to exclude categories from my homepage, but I want them to still display in the sidebar shown on the homepage, how can I do that? At the moment my code excludes from both the content area and the sidebar, and I am putting the code in the functions.php file: function exclude_category_home( $query ) { if ( $query->is_home ) { $query->set( 'cat', '-5, -34' ); } return $query; } add_filter( 'pre_get_posts', 'exclude_category_home' );
You may have to alter the loop on the homepage. Set it up in your index.php: if ( is_home() ) { query_posts( 'cat=-5,-34' ); } and you should be good to go.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
How to set a custom post type to not show up on the front end I use a custom post type in one of my sites for image slideshows. I have publicly queryable set to false/off but when Google crawls my site I see 404 errors for the URLs for my slideshows. I thought that by having publicly queryable off Wordpress would not create those front end URLs. How can I completely turn off the front end URLs and pages for my custom post type? ## EDIT By adding `'public' => false`, `'has_archive' => false`, `'publicly_queryable' => false`, and `'query_var' => false` I have successfully gotten rid of the 404 errors in Google. I also added the function provided by @Norcross just for good measure.
Another option would be to set a 301 redirect for all the slideshow CPTs to redirect somewhere (like the home page). This would get picked up by Google, and also make sure no one accidentally gets on them function rkv_slideshow_redirect() { global $wp_query; // redirect from 'slideshow' CPT to home page if ( is_post_type_archive('CPT_NAME_HERE') || is_singular('CPT_NAME_HERE') ) : $url = get_bloginfo('url'); wp_redirect( esc_url_raw( $url ), 301 ); exit(); endif; } add_action ( 'template_redirect', 'rkv_slideshow_redirect', 1);
stackexchange-wordpress
{ "answer_score": 9, "question_score": 11, "tags": "custom post types, front end" }
Get WP_Query query after execution? It it possible to get the configuration of a the latest called WP_Query? I need to use it for debugging. For example, if i run something like: $the_query = new WP_Query( $args ); ... Could i get the $args array later by doing something like `$the_query->args();` or something?
Try the `$query_vars` property: $the_query = new WP_Query( $args ); $query_arguments = $the_query->query_vars; Which should return an associative array of query variables. To test: var_dump( $query_arguments );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, query, wp parse args" }
Restrict access to the Trash folder in Posts I want to restrict users from deleting posts permanently. How do I restrict access to the Trash folder in Posts? This is the only page were the users can delete their posts **permanently**. The only solutions that I have so far is: 1) Adding this to stylesheet: li.trash { display: none; } But both me and you know that this is a dummy fix and more importantly, it just hides the link that goes to the Trash folder for **all** users. 2) Remove the capability `delete_posts` for none-editors. The problem with this is that the users will not be able to move their posts to the trash folder (which is a feature that is essential for my platform). Do you know of a better solution?
With the filter we prevent the `Trash` link from being printed. And with the action, redirect back to the post listing page if the user tries to access the URL directly (`/wp-admin/edit.php?post_status=trash&post_type=post`). add_filter( 'views_edit-post', 'wpse_74488_remove_trash_link' ); add_action( 'admin_head-edit.php', 'wpse_74488_block_trash_access' ); function wpse_74488_remove_trash_link( $views ) { if( !current_user_can( 'delete_plugins' ) ) unset( $views['trash'] ); return $views; } function wpse_74488_block_trash_access() { global $current_screen; if( 'post' != $current_screen->post_type || 'trash' != $_GET['post_status'] ) return; if( !current_user_can( 'delete_plugins' ) ) { wp_redirect( admin_url() . 'edit.php' ); exit; } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, content restriction, trash" }
Where in WP can I check history or log of updates of plugins etc? I need to find out what happened at a certain time when some of my admins made some plugin updates etc. So I need to check in admin the log of changes, updates etc. Where can I find that in WP admin?
You can't pull it in wp-admin you actually have to go look at the plugin in wordpress repository and see if they added there or to the plugin author's site for a changelog. That would be a nice feature for the future.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 21, "tags": "admin" }
How to downgrade plugin? I have installed a plugin, but it causes problem with get_the_excerpt() function in my theme. So, I need to downgrade that plugin. How to do that?
If that plugin is hosted on wordpress.org, go to the plugin page, click on the **developers** tab, and select an older version. Example for JetPack.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Execute shortcode only in another shortcode I wonder if it's possible to do a shortcode **only in another shortcode**. For example I got following code pieces: [heading]some pricing page[/heading] [pricing_box] [heading]Some title[/heading] [/pricing_box] Now I don't want to define one shortcode **heading** which would apply to both the nested one and the first level shortcode. I want the both **heading** shortcodes to produce different outputs. Of course, I could try to solve this by renaming one of the shortcodes to **title** or something, but this doesn't always result in optimal naming arrangements.
To use a different callback for the nested headings switch the shortcode handler in the `pricing_box` callback and restore the main handler before you return the string. add_shortcode( 'pricing_box', 'shortcode_pricing_box' ); add_shortcode( 'heading', 'shortcode_heading_main' ); function shortcode_pricing_box( $atts, $content = '' ) { // switch shortcode handlers add_shortcode( 'heading', 'shortcode_heading_pricing_box' ); $out = '<div class="pricing-box">' . do_shortcode( $content ) . '</div>'; // restore main handler add_shortcode( 'heading', 'shortcode_heading_main' ); return $out; } function shortcode_heading_main( $atts, $content = '' ) { return "<h2>$content</h2>"; } function shortcode_heading_pricing_box( $atts, $content = '' ) { return "<h3>$content</h3>"; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "shortcode" }
How to re-post an old post? I am in need of re-posting random posts to the front page of the blog to make them fresh. Is there any hook that could help me achieve it? Thanks.
You may use the Old Post Promoter plugin: < This plugin promotes old posts by sending them back onto the front page and into the RSS feed. It does it randomly choosing an eligible post and updating the publication timestamp. The post then appears to be the latest post on your WordPress blog. "You down with OPP? Yeah you know me!"
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts" }
How to Create Editable Blocks of Text for the Homepage? I'm making a site based on WordPress. It's not going to seem a blog or WP. Just a website. So WP acts like backend where the client can edit the text blocks. Question: * How can I put block of text on my designed template wich users can edit from admin panel? Let's say something like this: ![homepage wireframe]( The 3 top blocks (about us, mission, why us...), how do you fill them from admin panel? Or specific text from header or footer. Do I have to create 3 posts, and reference them on template through `get_post($id)`? Which is the best way to do it?
You have multiple options here, depending on the amount of flexibility you want to give the editor of the text blocks. 1. Create a custom loop with `WP_Query`. See our examples and the Codex page for usage. Then you print the excerpts of the page these boxes are linked to. You can use attachments (images) and the full formatting here. 2. Use widgets. See our examples and the Codex page. Limited formatting because the visual editor doesn’t work too well in widget forms. 3. Use a custom navigation menu and print the description. You can combine these methods: Use widgets for header and footer, `WP_Query` and page or post excerpts for the other boxes.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 11, "tags": "posts, text, static website" }
a one-off rewrite rule I have _one_ page that I need to change the URL for. Currently, the page resides at example.com/departments/human-resources/ (human-resources is a sub-page of /departments/ ) My client wants to maintain the legacy url for the hr department which is: < How can I rewrite any request for `^/hr/?$` to `^/departments/human-resources/$` but keep the URL the same? That is, nobody will ever see /departments/human-resources/. My current .htaccess looks like this: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> I've tried adding a rewrite rule that writes /hr/ to /dept/h-r/ before the index.php line, but this gives me a 404.
Redirection allows you to modify post slugs and keeps a history of them, pointing all requests for the history of a page to the same destination. It's useful for all sorts of other things too, but it will definitely solve this problem.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "url rewriting, htaccess, mod rewrite" }
block a page from logged out users and redirect to homepage How am I blocking certain pages from being viewed by logged out users? I have some pages like a dashboard for example that each user has to display their posts an is found in the top level like mysite.com/dashboard. I made a custom template and assigned it to the page "dashboard" but I need to block all non logged in users and limit to author level and up. If the user doesn't meet the criteria then I need to redirect them to the homepage. I tried placing this at the top of the template but it returned an error. get_currentuserinfo(); if (!( is_user_logged_in() && current_user_can( 'publish_posts' )) ) { wp_redirect(home_url()); return false; } But this leaves the error.. Warning: Cannot modify header information - headers already sent by ()
You have to hook in earlier, I would probably use `template_redirect`: add_action( 'template_redirect', 'wpse_74577_redirect' ); function wpse_74577_redirect() { // the code from your question }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pages, wp redirect" }
How to display site title with post title? Is it possible to have the site title prepended before each post title, separated by a hyphen? For example: [my site title] - [my post title]
function prepend_site_name($title) { return get_bloginfo('name').' - '.$title; } add_filter('the_title','prepend_site_name'); Like that?
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "wp admin" }
Large Media Library I'm looking to organize a large WordPress Movies/Actors site, with thousands of posters, screenshots, etc... I currently have the images in a directory structure like /actors/firstname_lastname/filename1, etc.. with a database matching each pathname with a movie. Some names may have thousands of images. I suppose I want to import these into WP media library, and start using them in WP. I don't know whether to attach them to a post, one post per name, or if there's a better approach. How would you solve this problem?
I would not do it post by post I would use a plugin so I can manage it more and present them in lightbox or as a gallery. Plus in the future if you want to blog or add news you can always use the posts for that. Nextgen Gallery has been around for some years and I manage tons of photos and I can export and import pics with no hassle. The built in wordpress gallery as an option sucks in my opinion. You should maybe get pixelmine plugin (cost some) if you want to steer away from the gallery look and have albums and such.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "gallery, media, media library" }
What hook is used to display the admin_bar on the front end? Or, how is the admin_bar displayed at all? I'm looking to display a similarly styled menu, but for all users who visit.
I believe you are talking about the admin_bar which has many hooks. You can read more about * wp_before_admin_bar_render * and wp_after_admin_bar_render in codex and actually wp source.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "hooks, admin bar" }
PHP Memory Limit Question I just moved to a dedicated server and I was wondering whether i need to do anything explicitly inside wordpress config files to increase the performance of the site, like setting an upper memory limit.. is this really needed? many thanks, Andy
Actually, you should take advantage of your server and move some of the load from the database (usually disk) to the memory. You could start by enabling the APC PHP extension and installing this plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "memory" }
About WordPress site security If I install WordPress on my server, does it mean that Akismet is installed automatically? If so - do I still need to create e-mail verification and captcha tools for improving site security (as I see WP does not have this features in itself). What is recommended for captcha test- simple php captcha or some graphical ajax invention (by drawing or moving objects etc)? My site will be rather plain, but will have user's comments on each page.
Akismet comes pre-installed with WordPress. You will, however, need to activate it from the 'Plugins' menu and sign up for an API key (free plans are available). And no, captchas are not needed (Akismet catches almost everything), but you can find a plugin to add one if you wish. If you're concerned about sercurity, I recommend the Better WP Security plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "security" }
load-* hook for dashboard I'm trying to add a screen option to the dashboard screen. I have a function like: my_function() { ... add_screen_option() ... } Now, I need to know the correct action hook $hook to use hooking in my function when the dashboard screen is loaded: add_action( "load-$hook", 'my_function' ); What should $hook be?
add_action( 'load-index.php', 'the_function', 1, 0 ); The `load-{page_hook}` hook works with the filename of the page to load.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "hooks, dashboard" }
Get all meta boxes values I want to list all the values of a custom metabox in a custom post type. Here is the code to get the one meta box in a single post <?php echo get_post_meta($post->ID, 'institution_location', true);?> but say I want to list all the meta boxes in the home page or a dropdown menu in a search form not just in a single page the metabox code add_meta_box( 'Location_metabox', __( 'Location ', 'twentyeleven' ), 'institution_location_metabox_output', 'institution', 'side' );
I tried to use WP_Query and it works fine. <?php $args = array('post_type' => 'institution'); $the_query = new WP_Query($args); while ( $the_query->have_posts() ) : $the_query->next_post(); $id= $the_query->post->ID; $location = get_post_meta($id, 'institution_location', true); echo $location; endwhile; ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "metabox" }
Referencing parent theme image from child theme Apologies if this has been answered elsewhere, but I've had some trouble finding the solution via Google. I've set up a parent theme and a child theme. Inside the parent theme I have a directory named img which contains a number of images I want to use in the child theme too. The problem is, I can't seem to find the best way to reference an image from the parent theme whilst inside the child theme. Surely there is a particular way to reference the path dynamically? Whilst in the child theme, using `<?php bloginfo('template_directory'); ?>/img/` seems to look for the `img` folder inside the child theme, but I am looking to reference the img folder inside the parent folder. Any help on this would be great!
You can use `<?php get_template_directory_uri(); ?>` to reference your parent theme folders. From the WordPress codex: _In the event a child theme is being used, the parent theme directory URI will be returned..._
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "child theme, parent theme" }
Post to inherit custom category background image from parent I have a custom field on a category where you can add an image. I have it as a background image to show on the category's archive page, like so: archives.php <body style="background:url('<?php echo z_taxonomy_image_url($cat->term_id); ?>')"> It uses the Categories Images plugin to achieve this. Is there a way for the posts in this parent category to inherit this background image? something like $cat->parent_id?
You can use this function to output the parent category ID and then style off of that. <?php function wpse_74737_category_top_parent_id($catid) { while ($catid) { $cat = get_category($catid); $catid = $cat -> category_parent; $catParent = $cat -> cat_ID; } return $catParent; } And then call this in your `body` class: `<?php echo wpse_74737_category_top_parent_id( $cat->term_id ); ?>`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, custom taxonomy, terms, custom background" }
How to set different cookies for logged in admin users and logged in non admin users? I would like to identify admin users and non-admin (but logged in) users through cookies. I need this feature because I use Hyper Cache (which uses cookies to identify those who send pages in cache): I would like to serve cached page to all users not logged in and to all users logged in but non-admin. The logged in admin users will not get cached pages.
You can use `current_user_can()` to detect what type of user is logged in, if any, then use `setcookie()` and `$_COOKIE` to test and set the necessary cookies. function wpse_74742_stop_cache_cookie() { if (current_user_can('admin')) { if (empty($_COOKIE['disable_cache'])) { setcookie('disable_cache', 1); } } } add_action('init', 'wpse_74742_stop_cache_cookie'); This is an extremely basic example. There are a lot of details to cookie management so you may want to do a bit of reading up on cookie paths, domains and expiration. You also may do better to simply set the cookie with the appropriate hook instead of relying on the user capabilities with the `admin_init` action: function wpse_74742_disable_admin_cache() { if (empty($_COOKIE['disable_cache'])) { setcookie('disable_cache', 1); } } add_action('admin_init', 'wpse_74742_disable_admin_cache');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "login, cookies" }
Add Input Field in Simple Model Contact Form (smcf) plugin I am using nice SMCF (Contact Form) want to add a wordpress post list Drop Down menu in "Simple Model Contact form" here what i added on line '195' to try look. $output .= "<div class='colmsg'><label for='smcf-message'>*" . __("Message", "smcf") . ": </label> <select name=""> <option>Post1</option> <option>Post2</option> <option>Post1</option></select></div><br/>"; after saving / uploading file, it showing Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in plugins/simplemodal-contact-form-smcf/smcf.php on line 201 please help me how to get post list in form. ?
It just wasn't concatenated correctly (i.e. misuse of single/double quotes). This'll work: $output .= '<div class="colmsg"><label for="smcf-message">*' . __("Message", "smcf") . ': </label> <select name=""> <option>Post1</option> <option>Post2</option> <option>Post1</option></select></div><br/>';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, plugin contact form 7" }
Search outside of the "loop" I am creating a blog using only Wordpress's backend. I have found functions to get latest posts (wp_get_recent_posts) and all the required data I need. I do this by including wp-load so I have access to WP's functions. However I cannot find anything that allows me to perform a search outside of Wordpress's theming loops as I have for the rest of the data. I was hoping there was a search function where I can pass it a search query that could be in title, body content or tag name. Am I missing something blindingly obvious in the documentation, there seems to be a function for everything else I need outside of WP's "loop".
You can use `get_posts()` with a search parameter: $results = get_posts( array( 's' => 'search term' ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "search" }