INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Custom priority with the_content filter based on user input Currently, in my plugin Contextual Related Posts, I have an option to automatically add the related posts to the content using add_filter('the_content,'ald_crp') I know I can change the priority of the filter by adding a number greater than 10 (which is WordPress default). add_filter('the_content,'ald_crp',20) However, what I would like to do is let the user set the priority of the filter from within the options page which I can use and set the_content filter accordingly. The plugin already has its own settings page. My plugins doesn't use classes. It uses functions. Any suggestions / code samples for this?
Save the priority in your options and pass that value to your `add_filter`: add_action( 'template_redirect', 'wpse_81687_prepare_filter' ); function wpse_81687_prepare_filter() { $my_options = get_option( 'my_options' ); $priority = isset ( $my_options['content_filter_priority'] ) ? $my_options['content_filter_priority'] : 10; add_filter( 'the_content', 'ald_crp', $priority ); } In my example I register the `the_content` filter during `template_redirect` because it is not needed earlier. You don’t need the filter in `wp-admin` or a login page. You could even use `the_post` as hook instead of `template_redirect`. But then … another piece of code might call `echo apply_filters('the_content', $some_text );` without calling `setup_postdata()` before.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, filters" }
Difference between Option_Group and Option_Name in Register_Settings I think the title pretty much says it all! I'm working my way through various tutorials on how to add an options page to my test plugin and am struggling to understand the `Register_Settings` function. Every tutorial I have found quotes the codex for the arguments then uses the same text in the `Option_Group` and `Option_Name` argument. Can someone explain it to me please?
The codex defines the function as: register_setting( $option_group, $option_name, $option_validate_function ); * `$option_group` is settings group name. Use when displaying on a settings page for example * `$option_name` is the database entry name * `$option_validate_function` is the callback for this database entry/this option. Most codex tutorials use an array of data in one `$option_name` but that's not required (just more efficient in terms of table rows). You can add multiple options with unique names under the same option group. **Usage** * `$option_name` is the name you access when using `get_option( $option_name )`. * `$option_group` is the group name used when creating security with `settings_fields( $option_group )`.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 8, "tags": "options, settings api, user registration" }
How to make page template with admin able to select NextGen Galleries to be part of the layout? I'm trying to make a product page template, editable by client, which will have 3 different NextGen Galleries per page. In the product page admin area, I want the client to be able to select which 3 NextGen galleries to display, and in which order. What do I put in my template page, and (I'm assuming) functions.php? Here's a mockup of an individual product page how I want it to be, so you can see what I mean: < I'm customising a theme, in which all the 'About the Product' fields etc are in the page template already, I just want to add selectable NextGen Galleries. I've tried googling this but I'm not sure of exactly what terminology I should be searching for, so any advice would be appreciated. Thankyou!
You can add galleries directly to a template by calling do_shortcode() to run the gallery shortcode. <?php echo do_shortcode('[nggallery id="1" template="example"]'); ?> Edit: sorry, writing decaffeinated so short attention span :) Add some custom fields to your product pages to let your client pick which gallery goes on that product. If you like, just use the Advanced Custom Fields plugin and its friend the NextGEN Gallery Field add-on, which will let you add drop-down lists of gallery names to your edit pages. Then in the template, get the value of each custom field and load the gallery using the shortcode as above, like this (replace 'gallery1' with your custom field names): <?php $gallery = get_post_meta(get_the_ID(), 'gallery1', true); if ($gallery) { echo do_shortcode("[nggallery id='$gallery' template='example']"); } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "page template, plugin nextgen gallery" }
Silently register plugin pages I am developing one of my first plugins, and have come across a error: > You do not have sufficient permissions to access this page The plugin has a wizard that uses several forms, obviously I don't want people selecting later forms using the menu. Is there a way to "silently" register a page? Basically, register the page without having it appear in any menu. (I don't like my work around)
The mighty Codex holds the answers: 1. If you're running into the »You do not have sufficient permissions to access this page.« message in a `wp_die()` screen, then you've hooked too early. The hook you should use is `admin_menu`. 2. `$parent_slug`: Use `NULL` or set to `options.php` if you want to create a page that doesn't appear in any menu
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugin development, admin menu" }
Help with this custom field conditional if no field is set display nothing I'm using the code below to display an image if the swap_select custom field value is true. If it's no it displays nothing. However when posts are first created no custom field exists. So what would the conditional be to account for no custom field at all and in that case display noithing? <?php $swap_value = get_post_meta($post->ID, 'swap_select', true); // check if the custom field has a value if($swap_value!= 'no') { echo '<img class="" src="thumbs/speechbubble_pink.png"/>'; } else{ } ?>
I prefer `empty` for this because it considers a lot of things to be "empty" besides just an empty string, and that is the behavior I usually want. Be aware of that though. I am not 100% sure what you are doing but... if( empty($swap_value) ) { // runs if no $swap_value, or an empty value } // OR if( !empty($swap_value) ) { // runs if $swap_value is set to something } Reference the PHP Docs for exactly what `empty` considers "empty" or "not empty".
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, conditional content" }
Text snippets shared across posts I'd like to add a "fast facts" section to a wordpress site - an area in the sidebar where snippets of text are rotated. Where is the best place to store things like this? Widgets don't really allow repeated items grouped in a good way & i don't want to add a post type as that would be available as a page with a URL
It sounds like you _do_ want a custom post type, you just want to set the `public` argument to `false`. The `register_post_type()` has lots of arguments that will let you do everything you probably want. Along with `public`, you'll probably set `has_archive` to `false`. Setting `show_ui` to `true` will allow you to manage the posts in the backend. If you want to group the "fast facts" in any way, register a taxonomy to go along with your post type. Obviously, you'll still have to fill in some blanks and write a widget to put into the sidebar, but I think this answers your main question.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "admin, database, sidebar" }
Contributor disable seeing others' posts How can I disallow contributors on my site from seeing what other posts are published on the site, and only see their own?
I hope you are talking about wp-admin section. If yes just place this code in your `functions.php` file add_action( 'load-edit.php', 'posts_for_current_contributor' ); function posts_for_current_contributor() { global $user_ID; if ( current_user_can( 'contributor' ) ) { if ( ! isset( $_GET['author'] ) ) { wp_redirect( add_query_arg( 'author', $user_ID ) ); exit; } } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "user roles" }
After being hacked Fatal error: Call to undefined function get_header() in 404.php on line 1 After having timthumb.php exploited. The site was upgraded to WP 3.5 It was compromised again, (wp-config included encrypted data as well as the functions.php in the wp-include directory. After reviewing various sites, I opted to remove ALL files (after backing up the site) and reinstall the code to insure no corrupted files, and to remove any unneeded files still lingering from the various theme/plugin/and versions of WordPress updates. The home page loads, but all links beyond that are unusable, giving this error Fatal error: Call to undefined function get_header() in ...404.php on line 1. The Header and 404 php files are in the root of the theme's directory, and there is not modification of the code. I've wiped the site clean twice now, and extracted the 3.5 install and theme back onto the site to ensure correct file placement.
"Generally this happens when someone has mistakenly put index.php from a theme in the WP install folder, where it overwrites the index.php that is the main WordPress file. Download WordPress again, and take the one file, index.php from its root folder, replacing the file you now have as index.php It sometimes means someone has loaded an entire theme into the root WP folder." You might also want to update your permalinks/htaccess if your homepage is working but pages beyond that are not.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "headers, installation, fatal error, hacked" }
Author's Id from wp list authors function I'm new in wordpress. I want to display all author list with its ID. I'm using `wp_list_authors` function but didn't get any author id from the author list. So, How can I get Author's ID in listing of all author?
You can use the following: // prepare arguments $args = array( // search only for Authors role 'role' => 'Author', // order results by display_name 'orderby' => 'display_name' ); // Create the WP_User_Query object $wp_user_query = new WP_User_Query($args); // Get the results $authors = $wp_user_query->get_results(); // Check for results if (!empty($authors)) { echo '<ul>'; // loop trough each author foreach ($authors as $author) { // get all the user's data $author_info = get_userdata($author->ID); echo '<li>'.$author->ID.' '.$author_info->first_name.' '.$author_info->last_name.'</li>'; } echo '</ul>'; } else { echo 'No authors found'; } For more reference see this.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "author, list authors" }
Date in the URL with The Events Calendar I am somewhat of a Wordpress beginner so please excuse any ignorance. I have installed the plugin The Events Calendar ( and it works pretty much perfectly. One issue I have is the URL format for an event, which based on the URL slug is `/upcoming-event/[event title]/`. If I have multiple events of the same name, the URL looks like `/upcoming-event/[event title]-2/`. This is undesirable, I would prefer to have URLs more like that possible with posts `/upcoming-event/[year]/[month]/[event title]`. On a whim, I attempted to copy in the format used for posts `/%year%/%monthnum%/%postname%/` but alas, no luck. I had a quick check to make sure it wasn't a PRO feature but it doesn't appear to be. So does anyone know if this is possible somehow?
You could just try to change the slug to the value you need for each event. The problem arises if you have the same event twice (or more) in the same month though. You will need to create a new title for the event. you can try this plug-in: < It might help you with changing the permalink structure for the events so you wont need to keep changing the slugs when you create events. But I don't think that will help with removing the number after the event title as that is the way WP core works for duplicate posts. Tri.be has a pretty good support team have you posted the question there?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugins, the events calendar" }
Our plugin tags not appearing in WordPress Plugin Repository We have an appointment calendar plugin at WordPress Plugin Repository. In our plugin **`readme.txt`** , we have already added tags like: === Appointment Calendar === Contributors: a.ankit, FARAZFRANK, harimaliya Link: Tags: appointment, booking, calendar, appointment scheduling calendar, appointment calendar Requires at least: 3.3+ Tested up to: 3.4.2 Stable tag: 2.4 **Readme Snap:** !enter image description here you can check our plugin **`readme.txt`** file at WordPress Plugin Repository: **here** But these tags are not appearing after plugin description at WordPress Plugin Repository. If anybody have any knowledge about this issue then help me. Thanks...
There was an attack yesterday on WP servers, make a small push and try again. First, run the readme validator and make sure yours matches as much as possible the official example.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, readme" }
Creat new admin url for custom post type I have a custom post type called newsletter. Once the newsletter is created I want to create a link to download the newsletter from the admin section (the newsletter post type is not accessible from the front end of the wordpress site). When the download link is clicked it will run a function in my plugin. The question is how do I register a url with wordpress that will do such a thing? I'm sure this is something pretty simple and I'm just missing it.
You want (probably) `add_submenu_page`. The first parameter-- the one listed as `$parent_slug` in the Codex is going to be `edit.php?post_type=your-post-type-name`, like this (mostly cribbed from the Codex page): function add_submenu_wpse_81844() { add_submenu_page( 'edit.php?post_type=your-post-type-name' , 'My Custom Submenu Page' , 'My Custom Submenu Page' , 'manage_options' , 'my-custom-submenu-page' , 'my_custom_submenu_page_callback' ); } add_action('admin_menu', 'add_submenu_wpse_81844'); Check the Codex for what the other parameters mean.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom post types, wp admin" }
Performance Gains of Relational DB Setup Our team is working on the 3rd of large WP sites for a client, and contrary to most "typical" WordPress setups, our projects are generally experience lots of requests, data pulls, and general content - if you saw (and could see) our site, you would be hard [word]pressed to know it was even a WP site. I've been examining performance, particularly on the database level, and we've implemented some basic caching for larger data sets. My question is - would we gain much in performance by taking some steps to improve the database in terms of structure? Such steps would include: * converting tables to InnoDB (our default is MyISAM) * setting up proper foreign-key relationships, such as wp_postmeta.post_id => wp_posts.ID Those are the only ones I've come up with so far, but there may be others. I've done work with various SQL engines, but I'm by no means a master of optimization on the database level.
I can't comment on foreign keys but moving to InnoDB would be a good idea for large scale. Although it's a little slower than MyISAM, it does row level locking, rather than table level locking. As a result saving a post or doing a lengthy operation or query won't lock the posts table, freezing the entire site while it waits for the table to unlock. For very large multisites it may be desirable to investigate HyperDB, which is what wordpress.com uses. Not DB related but you may want to look into the short init definition for AJAX calls
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "database, innodb" }
How to filter out an iframe from feed There is some iframe inside post content and I want to get rid of that iframe when the rss feeds are generated. To generate rss feeds, I'm showing full post content. I started looking at `strip_tags()` but it does pretty much the opposite: strip everything unless the desired tags. I'm wondering that maybe there is some hook and some wordpress-y form of solving this issue. I know I should do something like this: function rss_noiframe($content) { global $post; // filter out iframe here return $content; } add_filter('the_excerpt_rss', 'rss_noiframe'); add_filter('the_content_feed', 'rss_noiframe'); But I'm lost at this point. Any ideas? On demand by EAmann, here is some example code that isnt modified at all (it still appears in the feed, in fact): <iframe src=" frameborder="0" scrolling="no" width="500" height="375"></iframe>
One potential option is to use `preg_replace` to do a regex match on your content and replace the iframe with empty space. So this function: function rss_noiframe($content) { $content = preg_replace( '/<iframe(.*)\/iframe>/is', '', $content ); return $content; } add_filter('the_excerpt_rss', 'rss_noiframe'); add_filter('the_content_feed', 'rss_noiframe'); Should automatically convert any instances of `<iframe src=...>...</iframe>` to a blank.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "feed, iframe" }
Getting post by specific date in Advance Custom Field How can i get movies there are today in cinema, for example my code display the movies in time that shoud apear 16 January,17 January..., how can i display only the movies in this day. Ex: today is Wensday 16 January 2013, how can i get only the posts(movies) that shoud apear only today If i have 2 movies that premiere is on 16 i want to display only that. For the meta key i use a custom field -'meta_key' => 'premiera_cinema' - with this i select the day. <?php // Get today's date in the right format $todaysDate = date('Ymd'); ?> <?php $loop = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 3, 'meta_key' => 'premiera_cinema', 'meta_compare' => '>=', 'meta_value' => $todaysDate, 'orderby' => 'meta_value', 'order' => 'ASC' ) ); ?> <?php while ($loop->have_posts()) : $loop->the_post(); ?>
This will compare today's date to the date meta key and select posts with a dates that are **greater than or equal** : 'meta_compare' => '>=' If you want to match only today's date, change it to just **equal** : 'meta_compare' => '='
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "get posts, timestamp" }
WordPress Multisite Multiple child theme I have a mulisite setup and I am using one theme for multiple sites in it and each site have a custom layout and design. So for that I need to create a child-theme. But I don't know how to create multiple child theme for each site so I can add customization in each child theme style.css, footer.php, function.php, header.php e.g I am using theme canvas for all sites. then I created canvas-child and customized it for site1 now I need to customize it for other site2 then how I can create one more child theme with current main theme canvas to effect customization on site2.
You can copy your `canvas-child` folder and call it `canvas-child-2`, or similar. Then open up `style.css` in `canvas-child-2`, and edit the `Theme Name:`. Do this for as many different child themes you need. You will then need to enable the child themes for the sites you wish to use them on. Visit the _Sites_ menu in your Network Dashboard, and click the edit link under one of the sites. Switch to the **Themes** tab and click on the **Enable** link under the name of the theme you wish to use on this site. Do this for all sites you wish to use a custom child theme on. The final step is to activate the themes on the sites. Login to the site's administration dashboard and visit the _Themes_ menu. Click on the **Activate** link under the child theme you wish to use on this site. Do this for all sites you wish to use a custom child theme on.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 6, "tags": "multisite, child theme" }
Protocol neutral URLS with wp_enqueue_script (SSL issues)? How do I use wp_enqueue_script so that I get protocol neutral URLs? Here is how I'm currently using it: `<?php wp_enqueue_script('name', get_bloginfo('template_directory'). '/js/name.pack.js'); ?>` I saw that `home_url()` is protocol aware so I figured `theme_url()` would be also but I'm getting the error below when I use it. `Call to undefined function theme_url()`
You can't -- URLs must have a protocol for WordPress to enqueue them. What you can do, though, is detect which protocol to use and then use that. $protocol = is_ssl() ? 'https' : 'http'; $url = "$protocol://example.com/resource"; But for enqueuing scripts from your theme, you should use get_template_directory_uri() or get_stylesheet_directory_uri() which already handle SSL: wp_enqueue_script('name', get_stylesheet_directory_uri() . '/js/name.pack.js');
stackexchange-wordpress
{ "answer_score": 8, "question_score": 6, "tags": "wp enqueue script, ssl" }
wordpress illegal string offset 'parameter' error I am getting the error illegal string offset when creating a checkbox in the admin. my code look like this. <input type="checkbox" id="slideThre" name="custom_settings[checked]" value="1" <?php checked(1, $custom_options['checked']);?>/> There is no error when I check the box and save. The error appear when I uncheck the box and save. What could be wrong? thanks.
Checkboxes only send data when checked. When unchecked, there is no post (or get) data. You need to check if set using isset() if (isset($_POST['custom_settings']['checked'])) { /* it was ticked */ }
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "plugins, php, themes, html" }
Order posts by month - in custom taxonomy template I'm trying to show all posts posted under the month, so 2012 ## December post 1 post 2 ## November post 1 post 2 The posts are to appear under my custom taxonomy template, so taxonomy-pubyear.php and I'm able to retrive all the posts for that term using the basic loop. If I add get_the_year('F') in the loop then the same month will be displayed repeatedly but I need it displayed once and have all the corresponding posts show up under it, any help with this would be appreciated. Note: If I have post published under the same day, month and year then the above get_the_year('F') will show the month and display those posts below it, i want that functionality but without having to use the same published date.
Save the current month in a variable and check it for each post, only output it when it changes: $current_month = ''; while( have_posts() ): the_post(); $this_month = get_the_time( 'F' ); if( $this_month != $current_month ){ $current_month = $this_month; echo $current_month; } the_title(); endwhile;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, date time" }
What's a good tool for speed benchmarking? I am doing some optimisation on my site and would like to take some readings on page load speed in order to determine what works and what not. Since my internet connection is unreliable I cannot just test on how long it takes to download the page to my laptop, but I need an external reliable source to test. Any good tools/websites that do this?
Try either of these for your site, either one will guide you to better page load performance. < <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "performance" }
How do I use CSS or PHP to customize Wordpress Form Manager Plugin Table? I'm using **Wordpress Form Manager Plugin** to design a table to display race winners for an athletic event. <table class="fm-data"> <tbody> <tr> <td class="fm-item-cell-lane">7</td> <td class="fm-item-cell-bib">124</td> <td class="fm-item-cell-fullname">Person Two</td> <td class="fm-item-cell-country">USA</td> <td class="fm-item-cell-sb">11.20</td> <td class="fm-item-cell-pb">11.03</td> </tr> </tbody> </table> I would like to use the 3-letter country code together with some CSS and or PHP to dynamically display the country flag after the 3-letter code. For more info on the limitations and functions of the plugin: Form Manager's documentation Any Suggestions?
many ways to do it, not best but easiest is problably javascript: <script type="text/javascript"> jQuery('.fm-item-cell-country:contains("USA")').addClass('americanflag'); </script> from that you edit your css (which I guess you're more comfortable with), setting property for each class (.americanflag in that case) Hope that help a bit
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, css, table" }
Stop header code from showing in category page? Hi I'm using the code below to show different header images in my custom template archives. Only problem is that it is also showing the headers in the category templates. go to < that image at the top isn't suppose to be there, how do i get that to not show. <?php if ( ! is_home() ) { if ( get_post_type() == 'pretty-little-liars' ) { echo '<div id="headerimg"><img src=" } if ( get_post_type() == 'revenge' ) { echo '<div id="headerimg"><img src=" } if ( get_post_type() == 'grimm' ) { echo '<div id="headerimg"><img src=" } } ?>
You can achieve that by changing the conditional to if ( !is_home() && !is_archive() ) Also consider using `if` and `else if`. So your optimized code would be: <?php if ( !is_home() && !is_archive() ) { if ( get_post_type() == 'pretty-little-liars' ) { echo '<div id="headerimg"><img src=" } else if ( get_post_type() == 'revenge' ) { echo '<div id="headerimg"><img src=" } else if ( get_post_type() == 'grimm' ) { echo '<div id="headerimg"><img src=" } } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, php, categories, archives, headers" }
Optimal solution to develop a wordpress theme? What i was doing previously, are as follows - 1. I copy the wordpress base theme (like twentytwelve in wordpress 3.5) 2. Rename the folder and converted index.html of my HTML to index.php for wordpress theme. 3. Replace style.css with my current style.css. Is it the right way of theme development or some else better technique can be applied for theme development ? I google a lot for the theme development but 99% tutorials are only using index.php , style.css only(some only header/footer etc) although in the new version of wordpress 3.5 twentytwelve I found there are too many files in the theme. So for the client case I dont want to leave any core theme functionality provided these dummy themes, so is it the correct way I am following or for the best way I need to design and code for each file ?
I like to do this as follows: 1. Go to underscores.me, fill out the theme name, and download the theme. 2. Strip out the parts of this (somewhat clean) template that don't want to use. 3. Start building your own template with the functionality that you wrote. This way you will have a clean template to start with, and no core theme functionality provided by the theme you decided to use as a dummy. I don't know exactly if there is any "right" way to build your own theme, only that the Codex insist you use the WordPress Coding Standards, CSS Coding Standards and that you follow the design guidelines. I think that, except of the parts of the Codex a developer is free in how to develop a theme.
stackexchange-wordpress
{ "answer_score": 10, "question_score": 2, "tags": "theme development, themes, child theme" }
BuddyPress: What's the use of wp_bp_xprofile_data table and how does it get updated? I have a questions related to BuddyPress: What's the use of `wp_bp_xprofile_data` table? How does the data in the table get updated? And when any user updates his information - does the data in this table get updated?
The `wp_bp_xprofile_data` table holds all of the custom fields used on the front-end by BuddyPress. It is independent of the WordPress user meta. All of the functions that interact with this table can be found in `bp-xprofile/bp-xprofile-functions.php`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "database, buddypress, table" }
Pull the content out of a page I wanna pull the data from this area "see the red area on the image below" !enter image description here Out to a specific template I have a page template named page.php <div class="contentholder"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php comments_template( '', false ); ?> <?php endwhile; // end of the loop. ?> <br /> </div> but this just send me a comment field.. i need the text in the page and i need the header
While inside a query loop, this function will output the current posts title: the_title(); This function will output the content: the_content(); What I suspect has happened however is that you are instead calling `get_template_part( 'content', 'page' );` and expecting it to output the content for the page, when what it's actually doing is checking if there's a `content-page.php`, and including it if it's present, if not it checks for `content.php` and includes that, and because neither exist, it's doing nothing, and so you get no content. For more details on what `get_template_part` actually does, look here: < **EDIT*** Working snippet: <?php while ( have_posts() ) : the_post(); ?> <?php the_title(); ?> <?php the_content(); ?> <?php endwhile; // end of the loop. ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, cms" }
How can i do custom author list? My blog have many author. I can list all author. All Author list: <ul> <?php wp_list_authors('exclude_admin=0&optioncount=1&show_fullname=1&hide_empty=1'); ?> </ul> But I want to sort in a special way. For Example im currently viewing Tech category page, I want a list of author with these id (3,10,12). I will use this code in sidebar widget. And i need a metabox for select author id. Regards
I assume that you would be providing the author IDs in the widget options. And that the authors would be displayed in the order they were listed. Assuming the input would be -> 3,10,12 You can have the following code to display the authors with that user ID in that order: $user_ids = "3,10,12"; //this is assuming you already have the value stored in a variable //convert the comma separated string into an array $user_ids_array = explode(",", $user_ids); //display the list of users echo '<ul>'; foreach( $user_ids_array as $id ): $user = get_userdata( $id ); echo '<li>'.$user->ID.' '.$user->display_name.'</li>'; endforeach; echo '</ul>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, custom post types, custom field, metabox, list authors" }
How to use 'Event Manager Shortcodes' plugin via the php code? I am using Event Manager plugin. I want to use many of the shortcodes via php code. e.g [events_calendar]
In general, you can do any shortcode with `do_shortcode()` (see codex). But if they have a template function available, its probably best to use that. echo do_shortcode('[events_calendar]');
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins, shortcode" }
How to create an Single-Portfolio page? I created a portfolio page to show my works for my theme Everything is ok on my portfolio page, but when I click on an link to go to the portfolio object page, it uses the template's single.php page. I would like it to use the template page I created "single-portfolio.php". How do I do this?
You have to use the Slug of your Custom Post Type "portfolio" for the filename, as you pointed out, `single-portfolio.php` is correct if your slug is "portfolio". You just have to take one more step, create the file in the Theme directory (the same folder where your `single.php` is located). WordPress automatically selects the `single-portfolio.php` for the Portfolio CPT if the file is there, and if it is not there, it takes the `single.php`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "themes, pages, html" }
How to update BuddyPress xprofile fields programmatically? I update user info using `wp_update_user` function. I also need to update the table `wp_bp_xprofile_data`. Is there any function, where I can update data on `wp_bp_xprofile_data` table?
This is how I would update a field named 'Address': function updateAddress() { global $current_user; get_currentuserinfo(); $newAddress = '123 New Street'; xprofile_set_field_data('Address', $current_user->id, $newAddress); }
stackexchange-wordpress
{ "answer_score": 12, "question_score": 2, "tags": "functions, database, users, buddypress, table" }
How can I sort posts by the date and a custom meta field? I have `custom meta field` that I use for the post `rating`. So I want to display posts by the `date` and the `rating`, but only for the posts that have specific rating. For example, I want to display posts with rating above 3, and in this order: by the rating (highest first), but grouped by the date (today's best rated, then yesterday's best rated, etc.). Can I do it with `WP_Query($args=array())` class?
Basically, I am reading right out of the Codex page for `WP_Query`. You want a `meta_query` similar to this with an `orderby` parameter with the two values you want to order by. The first is dominant. $args = array( 'post_type' => 'post', 'meta_query' => array( array( 'key' => 'rating', 'value' => 3, 'compare' => '>' ) ), 'orderby' => 'rating post_date', 'order' => 'DESC' ); $query = new WP_Query( $args ); I don't know what your `rating` field is named and I don't have your posts and your ratings on my system so I can't test that. Hopefully that will get you started.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, custom field, wp query, post meta, order" }
Remove image classes from post thumbnail output I wish to remove the image classes generated by default in the output whenever post_thumbnail() is called - <img width="1024" height="768" src=" class="attachment-large wp-post-image" alt="Yet another example"> I've read a bit about the remove_action() filter and this seems the way to go but I'm not sure how to use it.
You might try something like this in your `functions.php`: //remove class from the_post_thumbnail function the_post_thumbnail_remove_class($output) { $output = preg_replace('/class=".*?"/', '', $output); return $output; } add_filter('post_thumbnail_html', 'the_post_thumbnail_remove_class');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "images, post thumbnails, customization" }
What is the difference with get_sidebar and dynamic_sidebar? What is the difference with `get_sidebar()` and `dynamic_sidebar()`? I was wondering which one I should use. Maybe one use widgets and the other one doesn't?
Please refer to the **`get_sidebar()`** and **`dynamic_sidebar()`** Codex entries. The `get_sidebar( $slug )` template tag includes the `sidebar-$slug.php` template-part file. The `dynamic_sidebar( $slug )` template tag outputs the `$slug` dynamic sidebar, as defined by `register_sidebar( array( 'id' => $slug ) )`.
stackexchange-wordpress
{ "answer_score": 21, "question_score": 17, "tags": "sidebar" }
Developing a wordpress.com shortcode I am looking to develop a shortcode that all wordpress.com users can use. Should I proceed with developing a plugin? I know users on wordpress.org can use the plugin but I am confused on how to make wordpress.com users use the shortcode as wordpress.com does not let the users to install a plugin. Is it done in the background by wordpress.com by looking up the plugins?
For anything related to adding code to wordpress.com you should contact automatic.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugin development, shortcode" }
send users logging in from wp-login.php directly to home page of site, rather than dashboard I am currently using a plugin called Sidebar Login which allows users to bypass the dashboard and go directly to the site. However, when users login via `/wp-login.php` (e.g. when they click on their verification links in their emails), they are once again sent to the dashboard. I would like for users to be able to click on their verification links and have them directed to the home page of the website where they can sign in through the sidebar login I have set up. Is this possible?
You can achieve this by using the Plugin Peter's Login Redirect. It allows you to send users to a specific page after login, based on the user capabilities. So you can allow administrators to go to the admin section, while members are redirected to the front page. If you want to prevent users from ever seeing the admin, insert something like this to your `functions.php`, depending on which users you want to allow in the admin you may have to change the capability. if ( is_admin() && !current_user_can('manage_options') ) { wp_redirect( get_bloginfo( 'url' ) ); } You can also hook a redirect function to `login_enqueue_scripts`, to send every user calling the login page to the homepage (same structure as above).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "login, dashboard, wp login form" }
Trying to put a search page on site i'm trying to put a search page on my site. I thought it would be simple, but I am having no success. I have put a form in my header.php (which I call in my search.php page (include "header.php")) that looks like that: <form action="<?php bloginfo("template_directory") ?>/search.php" method="get"> <input type="text" value="Votre recherche pour:" /> <input type="submit" value="soumettre" /> </form> But when I submit the search, I get this fatal error and I don't know what to do. Hopefully, you will be able to help. Thanks! Fatal error: Call to undefined function add_action() in C:\wamp\www\wordpress-3.5-fr_FR\wordpress\wp-content\themes\electrobangers\functions.php on line 2 Relevant code: add_action("init", "register_my_menus");
You `form` action value is wrong. It should be `home_url()`. WordPress will pick the search template automatically then. The search field has to use the name `s`: <input type=search name=s> Otherwise WordPress will not recognize the request as a search request. The error happens, because you included the `functions.php` somehow withut using the automatic by WordPress.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, pages, search" }
NextGEN Conditional Statement What I'd like to do is if the NextGEN gallery has more than one page (pagination) execute some code...I got close: <?php $nggpage = get_query_var('nggpage'); if ($nggpage > 1) { echo "duck"; } ?> This code appears on all pages but the first page, how do I make it work on the first page? Because if I use `$nggpage >= 1` it executes the code on all pages, even if there is no pagination...I want it to only execute the code if there is pagination. Any ideas? Thanks, Josh
I figured it out!! My final code looks like: <?php $images = intval($wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggpictures")); $ngg_options = nggGallery::get_option("ngg_options"); $maxElement = $ngg_options["galImages"]; if ($images > $maxElement) { echo "duck"; } ?> Basically the code checks see if the number of images IS larger than the number of images displayed per page...if it is larger I `echo` what I want it to do...if not, it does nothing.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, conditional content, plugin nextgen gallery" }
Does search.php autofilter The Loop? I just did a normal form that redirects the results from index.php to search.php, where I pasted the normal loop code of my index.php that displays the latest posts, and I noticed only the posts from my search query appears. I did not put any filters with $_GET in the loop, is it possible search.php automaticly filters the loop to get results that matches my search???
The loop doesn not display _the latest posts,_ it just shows the posts the main query has found. On your search page the main query returns search results, and you can change its order (we have plenty of examples for that on our site). WordPress looks for the parameter `s` or `/search/` in the request URI and decides to do a search query then. That’s what you see as results. You don’t have to do anything more, if you are happy with those results. It happens automatically.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, search" }
Echo post title in post I am looking to echo the post title at the beginning of each post. I've tried adding the following to `functions.php` with no luck: function add_post_content( $content ) { if ( ! is_feed() && ! is_home() ) { $content .= '<p>.get_post('post_title').</p>'; } return $content; } add_filter('the_content', 'add_post_content'); Should I be trying to update the `functions.php` file or `single.php`?
Use `the_title()`: function add_post_content($content) { if(!is_feed() && !is_home()) { $content = the_title( '<p>', '</p>', FALSE ) . $content; } return $content; } add_filter('the_content', 'add_post_content'); The first two arguments are for `$vefore` and `$after`. If a post doesn’t have a title, you get not extra markup. The last argument makes the function returning the string. Otherwise it would print it out immediately.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, title" }
can i limit editing specific custom fields to certain roles? i am writing a plugin that injects unescaped content (including javascript) into a post. i'm storing this content as a custom field, and am wondering if there are any built in ways to prevent users from editing specific custom fields.
Simply use a Custom Field with its name starting with an underscore, so it won't show up in the CF meta box, eg, **`_field_name`** instead of ~~`field_name`~~. It will be hidden for all roles, but if you are manipulating its value only through code, then no problem. If you need to manipulate the value on the edit screen, then you'll need a Custom Meta Box and control its appearance according to the user role. _[ **update** : looks like this kind of field can only be entered dynamically, it dumps an error if you try in the admin interface ]_
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, user roles" }
REQUIRED: Could not find wp_link_pages. See: wp_link_pages by Theme Checker I have run my theme through WordPress theme checker to see if it can be submitted to WordPress.org. I encountered this error: > REQUIRED: Could not find wp_link_pages. See: wp_link_pages But this is not true. I am using a custom function `wp_my_own_link_pages()` which is a replacement for `wp_link_pages()`. It generates pagination with a compatible HTML structure for the theme. Did I miss something required? How can I make this work?
First, this question should be asked on the Theme Reviewers mail-list, not at WPSE. If you want official answers, you should use the official communication channels. But to answer your question in brief: Themes that implement core features/functionality are **required** to support the core implementation of those features/functionality. Thus, the requirement to use `wp_link_pages()` is... a requirement. Note that if you need to modify the HTML markup of the generated pagination links, you can use the arguments passed to `wp_link_pages()`. Functions that are filterable can have filters applied, but wholesale replacement of core functions does not conform to the Guidelines.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, theme development, coding standards" }
Rotate images in header based on date I am new to WordPress and I would appreciate some cool advice here. I have changed the `header.php` file in the Editor to include an image. I wonder if it is possible to automatically display one of 9 possible images depending on the date (ie. rotate them)
The following code will cycle between the 9 pics. 1st day of the year = pic0, 2nd = pic1...359th = pic9, 360th = pic0, etc. <?php $pic_array = array( 'pic0', 'pic1', 'pic2', 'pic3', 'pic4', 'pic5', 'pic6', 'pic7', 'pic8', ); $d = (int) date('z') % 9; $todays_pic = $pic_array[$d]; echo $todays_pic; Hopefully you're not changing a parent theme's header.php!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "headers, header image" }
remove post and categories/tags count from right now dashboard widget I know it is easily possible to add a post-type count for a custom post type to the right now dashboard widget. However I wonder if it is also possible to remove stuff from this widget. E.g. I don't have normal posts on my current wordpress site and I don't need the count to say 0 posts and 0 categories and 0 tags all the time. Is it possible to remove those counts?
There is no filter in PHP, so we have to use JavaScript: add_action( 'admin_footer-index.php', 'wpse_82132_hide_rows' ); function wpse_82132_hide_rows() { $rows = array ( # 'posts', # 'pages', 'cats', // meoww! 'tags', # 'comments', # 'b_approved', # 'b-waiting', # 'b-spam', ); $find = '.' . join( ',.', $rows ); ?> <script> jQuery( function( $ ) { $("#dashboard_right_now").find('<?php echo $find; ?>').parent().addClass('hidden'); }); </script> <?php } ### Result !enter image description here To remove the widget completely: add_action( 'wp_dashboard_setup', 'wpse_82132_remove_rn_dashboard' ); function wpse_82132_remove_rn_dashboard() { remove_meta_box( 'dashboard_right_now', 'dashboard', 'normal' ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, widgets, dashboard" }
Change 'Back To Website' link in wp-login.php The login form on the page wp-login.php has a link at the bottom that says "Back to _website-name_ " This link always redirects to the home page I would like it to redirect to the page the user has come from. I imagine this requires a hook added to functions.php but I'm not sure how and could not find anything while searching. Any ideas?
You can achieve that using Javascript and `login_footer` action hook to change the `href` attribute of the `Back to` link: <?php add_action('login_footer', 'ad_login_footer'); function ad_login_footer() { $ref = wp_get_referer(); if ($ref) : ?> <script type="text/javascript"> jQuery(document).ready(function($){ $("p#backtoblog a").attr("href", '<?php echo esc_js($ref); ?>'); }); </script> <?php endif; } ?> **Edit:** Thanks to @brasofilo answer, you might need to load jQuery in `wp-login.php`. It might be loaded already by your theme or another plugin, so you have to check. To load jQuery in order to use the above code: add_action('login_head', 'jquery_for_wp_login'); function jquery_for_wp_login() { wp_print_scripts(array('jquery')); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "redirect, wp login form" }
1 post, 2 templates I want to be able to render post in two different styles (2 templates). For example, let's say I have the post ID 133, I would like two URLS to access it and so it renders where different template would apply. * lorem.com/render1/133 * lorem.com/render2/1333 for example... or it could be something like: * lorem.com/post/133 * and lorem.com/post/133?template=2 How would you do it?
Your best bet would probably be the Rewrite Endpoints API. The API allows you to create post URLs with endpoints like `lorem.com/post/133/json/` or `lorem.com/post/133/print/`. You'll find useful code examples in the link provided.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, templates, single" }
How to list only child categories? Is there any way to list the child categories only? I just want to filter the Parent Categories
The following code is to display the subcategory instead of parent . I am not sure this is the one as you are trying too. <ul> <?php $catsy = get_the_category(); $myCat = $catsy->cat_ID; wp_list_categories('orderby=id&child_of='.$myCat); ?> </ul>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "categories" }
Include tags in the body of a post it feel like this should be easy. I want to add the post tags inside the body of some posts. I was thinking that creating a shortcode may be the answer. I came across these 2 pieces of code: To display the tags... <p><?php the_tags(); ?></p> To create a shortcode... function show_current_year(){ return date('Y'); } add_shortcode('show_current_year', 'show_current_year'); I can't combine the 2! Can anyone help? The only other solution would be to insert the php directly in the post but I think I'd need a plug-in to do that and I'm a bit wary.
Just add `the_tags()` to the shortcode: function wpse_82190_tags(){ return the_tags(); } add_shortcode('tags', 'wpse_82190_tags');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "shortcode, tags" }
Get a post's ID How do I get a post's ID? I know I can use the_ID(), but I have to use it in The Loop. How can I get the post's ID without the loop? Because I think using the loop just to find the post's ID will slow down my script. Maybe i'm wrong. Please help me :) Thank you!
If you're on a singular page, sometime after `init` and all the query variables have all ben set up you can use `get_queried_object_id` or `get_queried_object`. <?php if (is_singular()) { $post_id = get_queried_object_id(); // or get the whole object $post = get_queried_object(); // or do the first one differently $post_id = get_queried_object()->ID; } You can also just "false start" the loop and get what you need. It probably won't slow down your script: WordPress fetchs all the queried posts at once, so the database hit has already happened. You might use this if you're not a singular page and need to get the first post's ID. <?php // start the loop the_post(); // get the ID $post_id = get_the_ID(); // back to normal rewind_posts();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, id" }
How to detect first visit of a user? I want to build an alert for users who visit my WordPress blog. Is there a conditional function like `is_home()` to detect if someone visits the blog the **first time**? I want to send the alert to every new user no matter on which site he entered.
No, there's nothing in the core like that. You can set a cookie and do it simply enough (warning: untested code follows). <?php function is_first_time() { if (isset($_COOKIE['_wp_first_time']) || is_user_logged_in()) { return false; } $domain = COOKIE_DOMAIN ? COOKIE_DOMAIN : $_SERVER['HTTP_HOST']; // expires in 30 days. setcookie('_wp_first_time', '1', time() + (WEEK_IN_SECONDS * 4), '/', $domain); return true; } if (is_first_time()) { // it's the user's first time, do stuff! } Just make sure you have output buffering turned on or use that before anything gets sent to the screen to make sure the cookie gets set.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "functions, users" }
Repositioning 'Reply' Link in Comments I'm calling my comments the ol' fashion way: <?php wp_list_comments('avatar_size=60'); ?> I would like to be able to position the 'Reply" link where I choose. Right now, it defaults to the bottom of the comment. Sure, I can move it via CSS - but what if I want to place it after the dater or username?
Use a custom callback to render the comment content. Inside of the callback function call `comment_reply_link()` wherever you need it: comment_reply_link( array_merge( $args, array ( 'add_below' => 'comment-body', 'depth' => $reply_depth, // + 1 to offer always a reply link for a consistent UI 'max_depth' => $args['max_depth'] + 1, 'before' => '<p class="reply-line">', 'after' => '</p>' ) ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "comments" }
How to show one page with two different templates I have a page template that I want to be able to show in two different modes: a regular mode and a bare-bones mode, where there is no header, footer, sidebar, etc. My hope is that I can get this done using a parent-child url, like so: Normal view: < Barebones view: < I assume I will need to edit header.php as well as footer.php to check whether or not they should show up, but how do I figure out the parent-child relationship, or is there an easier way to get this done?
Add an endpoint to your post permalink, name it `clean`. In your callback for `template_redirect` use a special `header.php` or none at all. Do not forget to call `exit;`; otherwise WordPress will load the default template files later.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "url rewriting, page template" }
$wpdb error (Call to a member function insert() on a non-object) I have very few knowledge on oo php and databases, and I am simply trying to insert data in my wp_pagesvisites table but I am having some trouble with this error message. This is my script: $wpdb->insert( 'wp_pagesvisites', array( 'Adresse_IP' => $ip, 'Post_ID' => $id, 'Timestamp' => $time ) ); Thanks for helping!
`$wpdb` is a global variable. You have to take it into your function’s scope first … global $wpdb; $wpdb->insert(); … or access it per `$GLOBALS` … $GLOBALS['wpdb']->insert(); And I would use always lowercase keys; this is just a useful convention.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "database, wpdb" }
Can this be done? Create 50x50 thumbnails of all existing featured images? Just trying to get a scope of work estimation for a project I need done. My wordpress theme has a custom menu that works best with featured image thumbnails that are 50x50 pixels in size. If the user builds their site after installing my theme, its no problem, since I'm ensuring that all uploads create a 50x50 thumbnail image. However, if the user installs my theme into an existing site, I have no way of knowing what size their thumbnails are. Is it possible to create a loop over the thumbnails and do this?
There are lots of plugins that do this one way or another including: * < * < I wouldn't recommend reinventing the wheel. If you're particularly worried about it, you might looking into TGM Plugin Activation to suggest to people in the Dashboard that they install and use the plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "post thumbnails" }
Check user's role and store in variable I am using **custom user roles** which I create and assign by using a plugin. I was wondering how I could retrieve the user's role and store it in a PHP variable. What I am trying to achieve is something like this: Let's say I created 3 custom user roles: `role_apple`, `role_banana` and `role_carrot` if ( 'role_apple' === $user_role ) { echo 'User is an apple'; } elseif ( 'role_banana' === $user_role ) { echo 'User is a bannana'; } How this can be achieved?
You don't need to store anything, just check the current logged in user via `user_can`: global $current_user; get_currentuserinfo(); if ( user_can( $current_user, "role_apple" ) ){ // do something }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, user roles" }
WP Supersized & Easy Fancybox Conflict I am using WP Supersized and Easy Fancybox Wordpress plugins. Everything is works fine till the point I am not clicking the link to open a fancybox. Image is opening perfectly just having some issues with the position. Its shifting towards the left on opening up. Here is the link to my demo page where I am using fancybox : < Regards.
I spotted out the answer for this. Here is the culprit the culprit: the jquery.animate-enhanced.js file that had been added since version 3.1.2 is creating the issue. Comment out this line : wp_register_script('jquery_animate_enhanced', content_url().'/plugins/wp-supersized/js/jquery.animate-enhanced.min.js',array('jquery'),self::supersized_jquery_animate_enhanced_version) probably on line 55 in this file: wp-content/plugins/wp-supersized/includes/WPSupersized.php This is working for me now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "jquery" }
wordfence scan warning on W3 Total Cache I use Wordfence plugin which scans server side plugins with original plugin files to see if anything was modified by hacker/cracker. Today I got a warning and it shows these modifications on /w3-total-cache/lib/W3/Cache/File.php !enter image description here should I be worried? Last time I read there is a W3 exploit going around.
That security hole in W3 Total Cache was associated with data leaking through an exploit, and not explicitly with hackers changing code (that could happen afterwards, of course, but what you show isn't this). The exploit has been fixed so just make sure your plugin is up to date. If unsure, disable / delete the plugin, then reinstall afresh from the plugin repository. That isn't to say that you haven't been hacked, of course. Look for other signs, like core files with dates different to neighbouring files, folders that shouldn't be there, etc. Have a read of the hacked FAQ on wordpress.org for starters.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "security, plugin w3 total cache" }
Insert a span inside widget title to give a different color to the second word I'm trying to make my widget titles two-colored; the first word white and the second one yellow. I have no idea how I can insert a span before the second word of every widget title so that I can put a color to the span.
/** * Wraps the first half of the provided string inside a span with the class lol_class. * * @param string $title The string. * @return string The modified string. */ function wpsa_82312_widget_title($title) { // Cut the title into two halves. $halves = explode(' ', $title, 2); // Throw first word inside a span. $title = '<span class="lol_class">' . $halves[0] . '</span>'; // Add the remaining words if any. if (isset($halves[1])) { $title = $title . ' ' . $halves[1]; } return $title; } // Hook our function into the WordPress system. add_filter('widget_title', 'wpsa_82312_widget_title'); > On a recent project, my client wanted graphical headers for the widgets on her WordPress blog. Unfortunately, widgets are not that easily themed. Nor can you do this in CSS.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 3, "tags": "widgets, css, title" }
A guide or tool for inserting bootstrap in underscores theme? I am looking for a guide or tool for inserting bootstrap in to underscores theme. Booststrap is a CSS framework and Underscores theme is starter theme with ultra-minimal CSS.
I created a theme for this purpose. More details: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "theme development" }
How to display links in specific page I have following links in content.php and i want to display in specific page with condition. Any ideas or suggestions? Thanks. * Home * Director’s speech * Projects * Our Vision * Volunteers * Inquiry
You can either create a custom page template, or just add the code to your regular `page.php`: if ( is_page( 'your-page-slug' ) ) { echo 'your links'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "posts" }
How does WooCommerce store products / product variations? / Free Script to import product variations? So I'm just working for a client right now importing CSVs of products to WooCommerce. I've imported a lot of products so far using an existing plugin, but don't want to buy the CSV Product Import Suite for $99 to import product variations. So... Can anyone help me to answer one of the following two questions: 1. Does anyone know a free WooCommerce plugin / script that will let me import product variations? 2. If not, can anyone explain to me HOW WooCommerce stores product variations in the MySQL database, so that I can write a script to import product variations? Cheers!!
This one is not as extensive as the woo product but works very well and you can easily modify it. Good luck. By the way, today, and I don't know for how long, woo is having a 50% discount on their plugins. Just go to their site. Here's your plugin link <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins" }
Wordpress admin bar showing pending comments which cannot be selected or modified after deleting parent page My Wordpress admin interface shows there are 4 pending comments, but I've already approved three and deleted one of them via Disqus comment moderation page, but the page they were posted on was later deleted. I then posted two comments myself on a test page, deleted the page, and they are still shown as pending on Wordpress admin. How do I remove them from pending comments list? Page the comments have been posted to is removed, so they do not have anything in "in response to" column, these comments also do not have a checkbox next to them, so I can't select them. There are also no options appearing when hovering above the comment on pending comments moderation page. I just recently installed WordPress to my site and it doesn't have anything custom but Disqus. * * * I am absolutely new to WordPress, so please explain each step of possible solution in detail.
You may want to try the next plugin: < **Note:** I haven't tested this plugin reproducing your issue exactly, but the plugin I created to delete all pending comments. Please let me know :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "comments" }
Get author custom image field URL to display on post page? I'm using advanced custom fields and have setup an image field for my users to add an image in their profile. I'd need to display this image on post pages, so i've tried the following... <?php $attachment_id = the_author_meta('author_logo'); ?> <?php echo the_author_meta('author_logo'); ?> <?php wp_get_attachment_image_src( $attachment_id )?> <?php wp_get_attachment_url( $attachment_id ); ?> The output is always the image attachment ID never the URL. What can I change to output the image path URL? Thanks
From codex: > The the_author_meta Template Tag displays the desired meta data for a user. If this tag is used within The Loop, the user ID value need not be specified, and the displayed data is that of the current post author. A user ID can be specified if this tag is used outside The Loop. > > If the meta field does not exist, nothing is printed. > > NOTE: Use get_the_author_meta() if you need to return (not display) the information. So, replace `the_author_meta()` with `get_the_author_meta()`. You can then use wp_get_attachment_image() to get an image element ready for outputting to the page. <?php $id = get_the_author_meta('author_logo'); if ($id) { echo wp_get_attachment_image($id); } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "images" }
Custom URL for all posts in Wordpress I have a wordpress site with static page as the front page. I want to have `/blog` to display the recent posts. How can I do that? thanks.
Create a page with a custom page template, then create a custom WP_Query object to return your last posts. You can get something like: <?php /* Template Name: Blog Page */ get_header(); $args = array( 'post_type' => 'any', #all post types 'posts_per_page' => 10 #get 10 posts ); $query = new WP_Query( $args ); if($query->have_posts()): while($query->have_posts()): $query->the_post(); the_title(); #display the title endwhile; endif; get_footer();
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "blog, frontpage" }
Reset Roles (or undo role changes on theme change) I am creating a theme that deletes some user roles that are not necessary and creates others. (It deletes author and contributor and renames subscriber). Everything works, but on theme deactivation, I want to readd all the roles I deleted. Do I have to manually go in and create the roles (author and contributor), manually adding in all the capabilities listed here: < ? There are two reasons I don't want to do this: 1. More code. 2. If capabilities and roles get updated, on every Wordpress update I'll have to manually check I'm adding the right capabilities back. There must be a better solution for undoing all role changes I made on deactivation. Right?
Use a plugin to manage roles, not a theme. Roles are not for presentation. In your plugin use `register_activation_hook()` and `register_deactivation_hook()` to add or remove new roles. Do not remove built-in roles, other plugins may rely on their existence.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user roles, capabilities, deactivation, reset" }
Remove duplicate attachments Here is the situation: I have an automated script that upload attachments and link each attachment to a specific post. By mistake, the script run multiple times and I have the following 1. More than one attachment post in the Media library for a single file (the different attachment posts have the same File URL). 2. One of these attachment is actually attached to the post. What I want to do is obviously is clean up the media library. I need to remove the attachment post without removing the file, and also make sure that I don't remove the ones that are actually attached to their posts. Any ideas?
function get_attachment_files(){ $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => 0 ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $post) { setup_postdata($post); wp_delete_post( $post->ID ); } } } add_action('admin_init','get_attachment_files'); adapted from: < I'd be careful of this though, because I am not sure it won't delete the images too. In fact, I think it will, but I am throwing it out there as fodder and not as a perfect solution. If you dig into `wp_delete_attachment` there is a filter called `wp_delete_file` that you might be able to use to trick the function into deleting files from a made-up directory, ie _not_ deleting your actual files, but I can't be certain.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 5, "tags": "attachments" }
How to remove the Theme Customization Button from the dashboard and themes options page? In my Wordpress theme that I've currently been building I do not take advantage of the Wordpress Theme Customization API. As much as I would like too, I've invested far too much time into my own personal theme options framework for changing things. This leads me to my question. How do I remove the blue, "Customize Your Site" button from the dashboard as well as link shown when viewing Appearance > Themes? I did some Googling, but my Google-Fu failed and couldn't find a solution that didn't use CSS or Javascript. Ideally a hook to remove it would be best. But if there is no clean way to do so, a JS and or CSS solution would be fine.
With the lastest version of WordPress (4.3) you can now natively remove the customizer's theme switch setting without resorting to CSS hacks. /** * Remove customizer options. * * @since 1.0.0 * @param object $wp_customize */ function ja_remove_customizer_options( $wp_customize ) { //$wp_customize->remove_section( 'static_front_page' ); //$wp_customize->remove_section( 'title_tagline' ); //$wp_customize->remove_section( 'nav' ); $wp_customize->remove_section( 'themes' ); } add_action( 'customize_register', 'ja_remove_customizer_options', 30 );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 7, "tags": "theme development, filters, hooks, theme customizer" }
Removing <p> tags around <div> tags I’d like to stop WP from wrapping `<p>` tags around `<div>` tags in the TineMCE editor … Here’s what I’ve got: function filter_ptags_on_images($content) { return preg_replace('/<p>([^>]*)<\/p>/i', '$1', $content); } add_filter('the_content', 'filter_ptags_on_images'); That removes all `<p>` tags around text but nothing that is wrapped in `<p><div>text</div></p>`. I’d also like to know a solution if I have nested `<div>` tags like `<p><div><div>text</div></div></p>`.
Greedy and Ungreedy modifier: `preg_replace( '/<p>(.+)<\/p>/Uuis', '$1', $content );` Tested with this script: <?php $c = array(); $c[] = '<p>text</p>'; $c[] = '<p><div>text</div></p>'; $c[] = '<p><div><div>text</div></div></p>'; foreach ( $c as $content ) { $e = preg_replace( '/<p>(.+)<\/p>/Uuis', '$1', $content ); var_dump( $e ); } Also try `remove_filter( 'the_content', 'wpautop' );`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "tinymce, wp autop" }
Is there any central control/access panel for several WordPress sites? We have many WordPress sites on different hosts with different domain names. Is there any solution for accessing all posts and settings with a central management tool? It's been very hard for us to open 10 sites in 10 tabs and set one desired configuration in all of them. I know that WordPress has a version for Multisite, but this is this useful for multi site on one domain? Or can we use it to host different sites on one host?
For remote management of many installations of WordPress, I know of two options, one paid, one free. > ### ManageWP > > ManageWP is a WordPress management console that gives users full power and complete control in managing virtually any number of WordPress sites in the easiest way possible. > ### InfiniteWP > > Manage multiple WordPress installations from a single dashboard using our free self hosted software. * * * As for **WordPress Multisite** , two references: * **Don’t Use WordPress MultiSite** \- making the right choice * and, from the same author, a very fine eBook for when you are going to use MS: **WordPress Multisite 101**
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "multisite, multisite user management, management" }
Add whitespace between Chinese and other letters I want to add a space between a Chinese character and a letter or a number to make the article more readable. For example: > GoogleApple2 > > Google Apple 2 But add the space manually is a hard work. How can I do it automatically? Maybe with CSS?
Interesting question. This could be a useful part of a specific language file. It cannot be done in CSS, because CSS is (mostly) character agnostic. But using a filter and PHP it _is_ possible and on topic: add_filter( 'the_content', 't5_chinese_spacing' ); function t5_chinese_spacing( $content ) { return preg_replace( '~([^\p{Han}]*)(\p{Han}+)([^\p{Han}])~imUxu', '\1 \2 \3', $content ); } Be aware your internal encoding has to be UTF-8 to make that work. While WordPress works with other encodings too, PHP needs UTF-8 for this. Read WordPress Database Charset and Collation Configuration to make sure everything is set up properly. Also note I am using PHP’s character class for Han unification here. This is not perfect, some punctuation marks Chinese writers might use are not included.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "filters, the content, encoding" }
A Wordpress site with more than one domain name / Parked domains i have one WordPress blog/site and want to point/map more than one domain name hosted/parked on my server. How do i do that *** _without** redirecting by .htaccess?_* Edit Im configure the related setting in cpanel or plesk in parked domain but wordpress dont recognized them. I want to know why cant i confure thet easy as config it for first domain name? And also want to how do that?
You can use a predefined constants that points to site URL. (from Codex) define('WP_SITEURL', ' define('WP_HOME', ' Small example define('WP_SITEURL', ' define('WP_HOME', '
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "redirect, domain, domain mapping" }
Styles are not loading when changing permalink to %postname%? Fist I was using default option of permalink and everything was fine (speed is ok, my own created theme is working fine) but now I change default structure to post name structure of permalink now I am not getting 404 error but the problems are : 1 - Whole website is loading very slow (pages,post) . 2 - My custom theme is not working fine means styles are not working on single page or single post. I checked my .htaccess file where the code is : # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /wordpress_1/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /wordpress_1/index.php [L] </IfModule> # END WordPress
What are you typing in the `src="xxxxxx"`? Do you have the absolute path or relative path to your style? If your not loading the CSS from your functions.php with `wp_enqueue_style` you should load it like this in your header to always get the correct URL to the file: `<link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_uri(); ?>">` **Update:** If you (for some reason unknown) want to keep your current file structure with the CSS outside your theme folder. Use this code instead: `<link href="<?php echo home_url( '/' ); ?>css/style.css" rel="stylesheet" type="text/css" />`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, css, performance" }
Add tag to post api wordpress I have been googling around but could not find the "add tag to post" api/codex. Does anyone know what it is ? Also, the "delete tag from post". Thanks.
You'll find an index of a good chunk of the WordPress API here on codex. The function you want is wp_set_post_tags(), but follow the links from that page to related functions. Edit: this should remove a tag from a post, per comment below // $post is your post object, e.g. from: global $post; // $target is tag you want to remove // get an array of current tags on post $tags = wp_get_post_tags($post->ID, array('fields' => 'names')); // remove selected tag from array $key = array_search($target, $tags); if ($key !== false) { unset($tags[$key]); } // set new list of tags, without $target wp_set_post_tags($post->ID, $tags, false);
stackexchange-wordpress
{ "answer_score": 6, "question_score": 6, "tags": "posts, tags" }
How to add add_meta_box to specific Page Template? I want to add **add_meta_box** to specific **page** type like Page Template, Like Product Template. I am using this article < to try it.
If your custom page template filename is `foobar.php`, you can use `get_post_meta()`: global $post; if ( 'foobar.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) { // The current page has the foobar template assigned // do something } Personally, I like calling this inside my `add_meta_boxes_page` callback, and wrapping it around the `add_meta_box()` call itself. function wpse82477_add_meta_boxes_page() { global $post; if ( 'foobar.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) { add_meta_box( $args ); } } add_action( 'add_meta_boxes_page', 'wpse82477_add_meta_boxes_page' ); You'll just need to instruct users to _save the page_ after assigning the template, so that the meta box appears.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 5, "tags": "custom field, pages, metabox" }
AJAX function needed (toggle text) I am looking for a function that will toggle text exactly as shown by pressing the "Phone" button on this website. Any help would be much appreciated.
I do not think you need any AJAX here, You can do this also using jQuery Slide method. < Try here < <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "ajax" }
Using template tags in external JS file I’d like to know how to use the `get_bloginfo( 'template_directory' )` tag in an external JS file. I just found out that it’s possible using the `wp_localize_script` function but I didn’t manage to get it to work … _functions.php_ wp_enqueue_script( 'custom_js' ); wp_localize_script('custom_js', 'wp_urls', array( 'template_dir' => get_bloginfo( 'template_directory' ) )); _header.php_ (beneath `wp_head();`) <script> alert(wp_urls.template_dir); </script>
It doesn't work because you haven't enqueued your script properly. If the script isn't printed, neither are the variables set by `wp_localize_script`. Please read a WP Codex entry on `wp_localize_script` function. You have to include a path to the script after the handle.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp localize script" }
Allow admin roles to add images to comment replies this may be a step too far but I publish occasional tutorials on my personal blog and sometimes in comments get asked questions where an image would be very helpful to include as the answer. I've done a plug-in search and also looked for code but come up with nothing. Is there any way I can allow those with Admin role to upload an image as part of their reply to a comment? I don't want to allow readers to upload images really. Also I'm not really looking to add a link to an image in the reply, I'd ideally like it in the comment reply itself. Just a 'too difficult' or 'can't be done' response would put me out of my misery :-)
The easiest and quickest way that you can do this is by downloading the Comment Images plugin and limit access to the upload feature by the function current_user_can. As the WP page demonstrates, use: if ( current_user_can('manage_options') ) { // Plugin code here } I had a **very** quick look at the plugin code and you may need to add this function to the `add_image_upload_form` function. All and all, this should only take you a few minutes to setup.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, comments, user roles" }
Add relevant tag to search results Tags are a major part of my platform. Using the default search, **if** the search term matches a tag, on the results page, I want it to display: <p>Are you looking for our <a href="TAG-URL">TAG-Name</a> page?</p> The tag must have at least one post attached to it, so no empty tags. What would be the _lightest_ solution to achieve this? Our search feature is used very frequently.
In functions.php: function wpse82525_link_search_to_tag() { // check if search archive is being displayed if( ! is_search() ) return; // get search query var $sqv = get_query_var( 's' ); // get tag base $tagbase = get_option( 'permalink_structure' ) ? get_option( 'tag_base' ) ? trailingslashit( get_option( 'tag_base' ) ) : 'tag/' : '?tag='; // return link if matching tag is found return ( get_term_by( 'slug', $sqv, 'post_tag' ) ) ? '<p>' . sprintf( __( 'Are you looking for our <a href="%1$s">%2$s</a> page?', 'txtdomain' ), home_url( $tagbase . sanitize_title_with_dashes( $sqv ) ), $sqv ) . '</p>' : ''; } In search.php: <?php echo wpse82525_link_search_to_tag(); ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "php, search, tags" }
Including javascript for a shortcode I'm creating a plugin that allows a user to use a shortcode. This shortcode depends on a bunch of javascript that needs to be present once the shortcode loads. I'm having issues trying to decide when and where to load the javascript. Pieces of the code that the shortcode spits out are elements that need to be present, but aren't available for jQuery to utilize. Is there a specific way of loading and attaching scripts that a shortcode relies on? function build_total_search_method( $atts ) { $shorcode_php_function = include( dirname(__FILE__) . "/includes/total_search.php" ); return $shorcode_php_function; } add_shortcode( 'total_search', 'build_total_search_method' ); This seems to work, but it also prints a `1` to the page. Is this method okay?
Use `wp_enqueue_script` in your shortcode handler, in WordPress >= 3.3 it will be added to the page in the `wp_footer` action. Pass any data you need from PHP to JavaScript via `wp_localize_script`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "jquery, shortcode, javascript, wp enqueue script, scripts" }
Insert a Featured Video I'm trying to put a video as featured in my theme, i mean, to be shown by the tag "the_post_thumbnail ('')", without using any plugin. Is this possible? Thank you!
No, it is not possible as-written in core. `the_post_thumbnail()` uses the ID of the attachment post-type that has been selected as the _featured image_ for the post, then outputs the image associated with that attachment post-type. You would have to filter `the_post_thumbnail()` in some manner, but your question specified "without a Plugin".
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, html, embed" }
Currency (price) formating on custom fields I need to format a custom field in admin area (post edit) as a currency, eq: 12.000,00 , with user typing only the numbers, the , and . automatic. Ive searched arround, with no sucess.. Anyone? thank The code i am trying to use to enqueue script in admin is function enqueue_admin() { wp_enqueue_script( 'jquery' ); //adding Jquery to admin. Not sure if is needed or already there wp_register_script( 'autonum', THEME_DIR . '/js/vendor/autoNumeric.js', array( 'jquery' ), '1', false ); //this is autoNumeric for currency format wp_enqueue_script( 'autonum' ); } add_action( 'admin_enqueue_scripts', 'enqueue_admin' ); Also, not sure if i need to change all the $ to JQuery in autoNumeric.js, because of wordpress compatibility
if you want to process the field after submitting, php's number_format function is what you need: $price = number_format( $number, 2, '.', ',' ); but if you want to change how the number is displayed as it's typed in, try jQuery autoNumeric
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom field" }
Shortcode return is printing a 1 afterward function build_total_search_method( $atts ) { $shorcode_php_function = include( dirname(__FILE__) . "/includes/total_search.php" ); return $shorcode_php_function; } add_shortcode( 'total_search', 'build_total_search_method' ); I've created a shortcode that returns an included PHP file instead of a string ... however, after the returned statement, there is a `1` printed. Two questions: 1) What is the `1` all about and how do I remove it? 2) Am I doing this properly?
You are returning the result of calling `include`. You want to grab the output of the included file and return than instead. Use output buffering to do that. function build_total_search_method( $atts ) { ob_start(); include( dirname(__FILE__) . "/includes/total_search.php" ); $shorcode_php_function = ob_get_clean(); return $shorcode_php_function; } add_shortcode( 'total_search', 'build_total_search_method' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins, jquery, shortcode, include" }
Is it possible to get a user with just the password field? I tried doing something like this: $user = $wpdb->get_row(' SELECT * FROM ' . $wpdb->users . ' WHERE user_pass = "' . wp_hash_password('password') . '"' ); But the `wp_hash_password` function generates a different string from the one in the database, is it possible? What I'd like to do is have a custom form in my template that just asks for a password (think of it like the username/pwd screen to the WP admin area without the username) so I'd hash whatever the user inputs, compare it with my DB and if it matches take that user and log him in.
Here's what I ended up doing in case someone else need a similar functionality: // Simple text password $client_password = $_POST['client_pwd']; $users = get_users(); // Iterate over all users and see if the password matches foreach ($users as $user) { // If it matches log the user in if (wp_check_password($client_password, $user->user_pass)) { $user = wp_signon( array( 'user_login' => $user->user_login, 'user_password' => $client_password ) ); if (!is_wp_error($user)) { // Redirect or do something else } } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "users, login, user roles, password" }
WP_Query arguments: Loop through custom post type - get all entries except excluded meta_key? Can't seem to find out what I'm doing wrong. $args = array( 'post_type' => 'wr_event', // my custom post type 'posts_per_page' => -1, // show all posts 'meta_query' => array( array( 'key' => 'event_announced', // a custom field either "on" or "off" 'value' => 'on', 'compare' => 'NOT IN' ) ) ); $loop = new WP_Query( $args ); So all I want to do is loop through all `wr_events` but if an event has the custom field `event_announced` (a checkbox) checked I'd like to exclude it. Ideas? I tried setting "on" or "off" for the `value` and tried different solutions for `compare`
Your current query will select posts that have a value in the key `event_announced` which does not equal `on`. What I think you want is `NOT EXISTS`, and you can omit `value`, since you are querying for posts that don't have the key, hence, it will have no value. Note that `NOT EXISTS` is only available in WordPress 3.5+
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, metabox, meta query" }
How to add an excerpt and read more link to a page? I've a custom/static "homepage.php" in my templates directory at my WordPress. Now I need to show differents "page excerpts" in my homepage, but I don't know what should be do it. At this moment I've in my "functions.php" de following function: function excerpt_page() { add_post_type_support( 'page', 'excerpt' ); } add_action('init', 'excerpt_page'); With this function, I've in my Page editor a new field available where I can put an summary of the page. Somebody has any idea?
Thank you very much! Finally, I've succeeded with the following code :D <?php $pages = get_pages('include=10,20,30,40,50,60'); foreach ($pages as $page) { $featured_content = '<div class="four columns">'. '<h4><a href="'. get_page_link($page->ID) .'" title="'. $page->post_title .'">'. $page->post_title .'</a></h4>' . '<p>'. $page->post_excerpt .'</p>' . '</div>'; echo $featured_content; }; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, pages, excerpt, read more" }
Screenshot are not showing up on plugin page I know its quite common now, But I cant find out where I am doing wrong. I have screenshot placed at the right place (both trunk and tag/1.0 ) and used the same tag i.e 1.0 in readmen.txt but still they are not showing up on plugin's screenshots tab. Read me file < Plugin page. < Can anyone notice a problem somewhere?
I think there's a problem with your .png's. Are they truly .png files, or possibly .jpg/.gif just renamed to .png? Try saving as a .gif or .jpg and re-upload. Sidenote: unless you need your users to have the screenshots in the plugin .zip, you can upload them to the SVN assets directory instead, and it won't be included in the .zip. See Otto's post.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugin development" }
Inserting into WP DB I had initially asked a question based on my code (which has since been removed), I need some help/guidance in creating a plugin. Scenario: I have created a custom post type (CPT), now I need to insert values into the CPT from a database table external to the wp environment. This routine needs to run once every hour, no of rows can range from 50 - 500. What is my best course of action? Side question: Do I separate my CPT code from the insert routine code?
Use **wp_cron** to run a job every hour. < Use **$wpdb->get_results** to fetch data from your external table. Example: $q = "SELECT * FROM my_table"; $results = $wpdb->get_results($q, OBJECT); foreach ( $results as $result) { } Insert new CPT-posts using **wp_insert_post()** <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugin development, database" }
A Specific Blog post to be assigned as the landing page of my wordpress blog Is it possible for a specific blog post (in wordpress) to be the landing page? For example my domain name is _www.overflowingstupidity.com_ and I have this blog entitled post _"How to burn your house down in 3 easy steps"_ Whenever a user clicks or type in the url bar of the web browser my domain name, he/she will directed and landed on my blog post "How to burn your house down in 3 easy steps" instead of the default index.php file of my wordpress blog. Is that possible? IF YES, can you point out to me how?
1. Edit the blog post and copy the contents. 2. Create a new page and paste that content. Make sure you use the same title. 3. Now Go to < 4. Click **A static page** and choose your blog post. !enter image description here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, seo" }
Delete all associated media when custom post type removed Basically I have so many images associated with custom post type that I need to be able to safely delete all related media on removal from trash. Is there a safe way of doing this?
Is your post to image association custom? If not attachments should be automatically deleted by Wordpess. If the connection is custom, Wordpress provides a delete_post action that fires before and after a post is deleted, it will pass the ID of the post so you can use that to delete all custom content associated with it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom post types, media library" }
Disable sticky option for specific categories Is there a way to disable the sticky option on posts in specific categories?
I ended up going with another approach. I check to see what the current user's role is, then if the role is 'author', enqueued a CSS file to hide the sticky option's checkbox. In the theme's functions.php file: function hide_sticky_option($hook) { global $current_user; if('post.php'== $hook || 'post-new.php'==$hook){ $role = array_shift($current_user->roles); //get role of current user if($role=='author'){ //if role of current user is 'author' wp_enqueue_style('hide_sticky_option', get_template_directory_uri() . '/css/admin-post-style.css' ); } } } add_action( 'admin_enqueue_scripts', 'hide_sticky_option' ); admin-post-style.css: #sticky-span { display:none !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, categories, theme development" }
Wordpress "Loop" with large set of results I'm not sure the appropriate terminology but I have a wordpress "loop" for a custom post type that has roughly 300 results that all get displayed on a single page (no paging). The causes an enormous load on the DB server because for every "post" in the "loop" there are like N database calls (the_title, has_post_thumbnail, get_post_thumbnail_id, the_content, get_post_meta, etc..). What is the wordpress way of optimizing this? For something like this do most developers just drop to doing queries with $wpdb or is the wordpress way to cache the page and move on? I looked at doing straight $wpdb sql queries but grabbing the relevant data (especially images associated with the post) is less then intuitive.
You can use the Transients API to cache the entire HTML output so the queries are not done every time the page is loaded: $transient = 'my-300-posts'; $timeout = 3600; // 1 hour if ( false === $out = get_transient( $transient ) ) { $args = array( YOUR ARGS GO HERE ); $posts = get_posts( $args ); if ( $posts ) { foreach ( $posts as $post ) { $out .= get_the_title( $post->ID ); $out .= // whatever else you want to output... } } if ( $out ) { set_transient( $transient, $out, $timeout ); } } echo $out; However, you're still serving 300 post thumbnails on one page load, which is a lot of data to transfer. (You also need to delete the transient on the `save_post` and `delete_post` hooks) Maybe you'd be better off with infinite scrolling? It's an option in the Jetpack plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "custom post types, loop" }
Cannot login to admin panel in multisite install if subdomain is added to hosts file This is my case.I created a multi-site installation where users can register and be provided with a subdomain. As of this time, the administrator has not yet enable the creation of sub-domains in the apache configuration, so I manually added the newly created subdomains (from my testing) to my hosts file. After registration, it works but it will only access the front end. If I will logged-in, e.g. < it won't allow me to logged-in to the backend even though the logged-in details are correct? Any clues what is causing this? Is this related to a cookie? Thanks for any ideas..
The problem is in the server configuration. After the administrator fix the subdomain issue. Everything is working fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite" }
Add Commas Between Menu Items? I created a menu in wordpress in the Menus section of the backend is there any way to display the menu links with commas so it displays as `Link1, Link2, Link3, Link4`?
Use a very simple custom walker … class WPSE_82726_Comma_Walker extends Walker { public function walk( $elements, $max_depth ) { $list = array (); foreach ( $elements as $item ) $list[] = "<a href='$item->url'>$item->title</a>"; return join( ', ', $list ); } } … and call your menu like this: wp_nav_menu( array ( 'theme_location' => 'your_registered_theme_location', 'walker' => new WPSE_82726_Comma_Walker, 'items_wrap' => '<p class="menu">%3$s</p>' ) ); Fast and efficient. :)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "menus" }
Get categories for a specific post - Custom post type I'm trying to retrieve all the categories which are related to a specific post, using the `wp_get_post_categories()` function. The problem is that it is a custom post type, so I tried sending it in the $args array : wp_get_post_categories($id,array('post_type'=>'product')); but that returned an empty array as well. What is the correct way of doing it?
Are you sure it a `category`, and not a custom taxonomy? If it is a category try: var_dump( wp_get_post_categories( $id ) ); or its equivalent since `category` is a taxonomy: var_dump( wp_get_object_terms( $id, 'category' ) );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "custom post types, categories" }
Custom Post Type Taxonomies -Posts not showing in Category or Tag pages I have a made a custom post type called "Member Resources" the posts under this CPT have a few taxonomies such as categories and tags. Tags = "Diversity" Categories = "Guidance" When I go to the following urls: www.domain.com/tags/diversity www.domain.com/tags/guidance No posts appear. Though I have set public => true on the CPT function. Posts are displaying if you go to the Member Resources archive page though, so they are displaying, but not when you filter them by taxonomies. Any help would be appreciated! Thanks.
You were close with the code you posted in your comment. The issue is that you only tested for `is_main_query`, which will limit every query on your site to that single post type. function wpa82763_custom_type_in_categories( $query ) { if ( $query->is_main_query() && ( $query->is_category() || $query->is_tag() ) ) { $query->set( 'post_type', array( 'post', 'resource' ) ); } } add_action( 'pre_get_posts', 'wpa82763_custom_type_in_categories' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, php, custom taxonomy, loop, templates" }
echo menu_order value in my theme I thought this would be a simple task, but I cannot find anything on google. I would simply like to echo the meun_order value in my loop. I tried this but it's not in the post_meta table, its in the post's table. <?php echo get_post_meta($post->ID, 'menu_order', true); ?> Can anyone help please? Thanks Josh
You can't use `get_post_meta` since the `menu_order` is stored in the `posts` table, like you said. But you can set up an easy database query to get the value. $menu_o = $wpdb->get_var( "SELECT menu_order FROM $wpdb->posts WHERE ID=" . $post->ID ); echo $menu_o;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "menu order" }
Child Theme Variables In my theme, I used this: <div id="brickwall" data-brickinvert="<?php echo brickAlign(); ?>"> I put the code into functions.php: function brickAlign() { $a = "true"; return $a; } Now in the child theme, I would like to change $a to false. Then in child theme my html would look like: <div id="brickwall" data-brickinvert="false"> I want to keep the function name the same, so that I won't have to copy all the files to change one variable. But of course I cannot put function with same name in child. I tried using global, but it caused errors. I also tried to do filters but my bleeping computer was having none of that either. The reason is so I can pass a variable into my Masonry jQuery script using the html data attribute, for aligning my bricks to top or to bottom, depending on which theme I'm in, parent or child. Thanks for any advice!
You can make your function filterable: function brickAlign() { $a = "true"; return apply_filters( 'brick_align', $a ); } Then, in your child Theme, add a filter callback: function child_theme_filter_brick_align( $a ) { return 'false'; } add_filter( 'brick_align', 'child_theme_filter_brick_align' ); Alternately, you could pass a parameter to your function: function brickAlign( $value = 'true' ) { // Note: you should add some error-checking here $a = $value; return $a; } Then, in your Child Theme, call the function like so: <?php brickAlign( 'false' ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "child theme, variables" }
WordPress Multisite - get_plugin_data() I use WordPress Multisite. I have multiple sites with plugins installed. I can successfully get a list of the plugin paths with the option value `active_plugins` from each site. I can not get additional data from `get_plugin data`. **I use this code:** $plugins = get_blog_option($blog_id, 'active_plugins'); foreach( $plugins as $plugin ) { var_dump( get_plugin_data($plugin) ); } **The error message:** " _Warning: fopen(akismet/akismet.php) [function.fopen]: failed to open stream: No such file or directory in C:\wamp\www\blogs\multisite\wp-includes\functions.php on line 3493_ " If this is not working on a multisite environment, is there a better way?
The problem is the value inside the var `$plugin`. The function `get_plugin_data` will use the completed path, like `/var/www/wp/wp-content/plugins/akismet/akismet.php`. Add the path before your plugin-folder and it works. I think you can use the constant `WP_PLUGIN_DIR`.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, multisite, get plugin data" }
How can i add a random redirect button in wordpress? I need a random redirect button just like 9gag.com. I know that i need a add a rewrite rule but i dont know how to do this I tried to use plugins and other codes, but none worked.
you can use this code add_action('init','random_add_rewrite'); function random_add_rewrite() { global $wp; $wp->add_query_var('random'); add_rewrite_rule('random/?$', 'index.php?random=1', 'top'); } add_action('template_redirect','random_template'); function random_template() { if (get_query_var('random') == 1) { $posts = get_posts('post_type=post&orderby=rand&numberposts=1'); foreach($posts as $post) { $link = get_permalink($post); } wp_redirect($link,307); exit; } } ANd then use this for random redirect <a href=" >Random Post</a>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "plugins, buttons" }
How to display products name in a non-alphabetical order, in a custom field (taxonomy)? Now the order is: **apples, oranges, pears**. But I want to be in a random order, for ex: **oranges, apples, pears**. Or to write them in a order that I want. Is this possible? Taxonomy is like that: 'fruits' => array( 'post-types' => array('products'), 'name' => 'Fruits', 'slug' => 'fruits', 'type' => 'tags' ),
**[SOLVED] This do the Job:** function set_the_terms_in_order ( $terms, $id, $taxonomy ) { $terms = wp_cache_get( $id, "{$taxonomy}_relationships_sorted" ); if ( false === $terms ) { $terms = wp_get_object_terms( $id, $taxonomy, array( 'orderby' => 'term_order' ) ); wp_cache_add($id, $terms, $taxonomy . '_relationships_sorted'); } return $terms; } add_filter( 'get_the_terms', 'set_the_terms_in_order' , 10, 4 ); function do_the_terms_in_order () { global $wp_taxonomies; //fixed missing semicolon // the following relates to tags, but you can add more lines like this for any taxonomy $wp_taxonomies['post_tag']->sort = true; $wp_taxonomies['post_tag']->args = array( 'orderby' => 'term_order' ); } add_action( 'init', 'do_the_terms_in_order'); **Credit goes here:** Change order of Custom Taxonomy List
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, custom taxonomy, custom field, taxonomy" }
How to use a .edu domain with WordPress? I work with a university that already has a domain name that ends in `.edu` (clari.buffalo.edu). I want to use this domain name as we have decided to migrate our web page to WordPress. From the sign up page, it appears that `.edu` is not supported. Is this true? If not, how can I use a `.edu` name with WordPress?
I think you're confusing `wordpress.org` vs `wordpress.com`. If `wordpress.com` is what you're looking for, this isn't the place. Per the About page of WPSE, > Don't ask about... WordPress.com support issues Now, if you're referring to using self hosted WordPress (`wordpress.org`) with a `.edu` domain, there are no limitation on domain extensions (afaik) and you should be able to set it up no problem as long as you have: * Somewhere to host it * The ability to point your domain to that hosting For info on setting up self hosted WordPress, read more about Installing WordPress. The items under Learn How to use WordPress may be helpful for you as well.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "domain" }
Custom Fields Not Showing I have this custom field for a post: key: price value: 2000 I've added this to my loop: <div class="buyitnow"><?php $price = get_post_meta($post->ID, 'price', true); if ( $price ) { ?> Price: $<?php echo number_format($price ,",",",",","); ?> <?php } else {} ?></div> But all I'm getting is: Price: $
You have `number_format` wrong. The second parameter should be a number and you have a string-- a comma. What you want is something like echo number_format($price,2,",",",");
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }