INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Alternate text if shortcode returns no data I'm using some plugins like beer list from Rescuethemes, and an event list, that use a shortcode to display a list of items. I put the shortcode into a Page, and it shows the data. If the shortcode evaluates to no data, like no beers in this category, or no upcoming events, I'd like to show alternate text, like "There are no upcoming events". What is the best way to accomplish this? Is this something I can do as a conditional in the Page itself? Am I better off just doing the check in the plugin itself and tweaking the return value? Does something like this belong in a Page Template?
You should do this in the shortcode/plugin itself. An easy way to do it may be something like this: // if the shortcodes empty: if ( empty( $shortcode_content ) ) { // set a default nothing found message $shortcode_content = 'Sorry! Nothing found'; } return $shortcode_content;
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "shortcode, conditional content" }
Text Widget creates a <li> I've got a basic text widget and, outside the standard `<div class="textwidget">` wrapper there is a `<li id="text-5" class="widget widget_text">` (which I have not added when creating the sidebar in `functions.php` or added when adding a text widget from the dashboard). i.e. the full code looks like this: <li id="text-5" class="widget widget_text"> <div class="textwidget"> <my content> </div> </li> I'm at a loss where this `li` comes from. Any idea why and how I can get rid of it?
I think WordPress widgets create li tags on default. If you want the bullet points removed you could fix that with a css approach. .widget li { list-style: none; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 8, "tags": "widgets, register sidebar" }
How to add page using HTML, CSS and JS? So I have a client who wants a little extra that is beyond capabilities of my wordpress theme that I have purchased. I know through html, css and js I can create it from scratch (they want animations and a neat looking landing page). I was wondering if there was a way or any plugins that I can use to directly create a page using all of the code. Sorry if I am not explaining my question well!
You can create custom templates in WordPress defining the template name at the top of the template. This is a basic template that should help you get started. You can save your template with a file name like tmp-mycustomname.php and put it in your theme. You probably should create a child theme where you can save this custom template and add additional CSS without losing it if the client updates the theme. <?php /* * Template Name: Template name goes here */ ?> <?php get_header(); ?> <div class="row"> <div class="col-md-12"> Your content can go here. <script> alert ("my javascript is working"); </script> </div> </div> <?php get_footer(); ?> Once your template has been created go ahead to pages > add new. Then you should see something like this where you can find the custom template in the dropdown. ![page template]( Helpful links: < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, css, html" }
Which is the best way to incorporate custom fonts? I believe there are 3 valid methods of incorporating custom fonts: 1. put a link to them in the header 2. enqueue them in functions.php 3. add them with @font-face in style.css Which is the best way to do it? Is any method loading faster than the other?
Depends on the source. If they are locally hosted, then they should be in the CSS files using @font-face. If they come from a service like Adobe Type Kit or Google Fonts, then they have to be enqueued in the functions.php to go into the wp_head() function. Edit: I forgot to mention that there are some plugins that can handle this for you. I personally use Type Kit and I have seen WordPress plugins where you simply enter in the kit ID Adobe gives you and it takes care of insertion.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp enqueue style, css" }
Wordpress Update 4.3.1 Hello there i have updated the wordpress to 4.3.1 now its showing me the following error please help Catchable fatal error: Object of class WP_Error could not be converted to string in /home1/dcp1997/public_html/wp-includes/default-constants.php on line 116
this is the line causing the problem for you. define( 'WP_CONTENT_URL', get_option('siteurl') . '/wp-content'); this could be get_option('siteurl') is not a string. please check what you having at `wp-option` table and `siteurl` row. If possible check what you are getting when you run `get_option('siteurl');` this line
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wordpress version" }
WordPress updates defined vs add_filter? I'm trying to create a WordPress update automation plugin. here I got two option to make enable and disable the updates. 1. Via define ex :`defined( 'AUTOMATIC_UPDATER_DISABLED',true )` 2.via add_filter ex:`add_filter( 'allow_major_auto_core_updates', '__return_true', 1 );` my problem is if I have disabled the updates via `define` and also have enabled it via `add_filter` which one will work ? does `add_filter` override 'define'? or `define` override 'add_filter'?
Skimming through the `Core_Upgrader::should_update_to_version()` method, it looks like we **can override** the defined( 'WP_AUTO_UPDATE_CORE' ) // true (all), false, minor check, used to setup the local _boolean_ variables`$upgrade_dev`, `$upgrade_minor` and `$upgrade_major`, with the following filters: ... apply_filters( 'allow_dev_auto_core_updates', $upgrade_dev ) ... apply_filters( 'allow_minor_auto_core_updates', $upgrade_minor ) ... apply_filters( 'allow_major_auto_core_updates', $upgrade_major ) ... So these filters have the _last word_ over the `WP_AUTO_UPDATE_CORE` constant check. Similarly, the `automatic_updater_disabled` filter can override the `AUTOMATIC_UPDATER_DISABLED` constant check. But note that we can't override the constant itself.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 6, "tags": "plugin development, updates, automatic updates, options" }
Ordering posts by custom field and grouped by month I need display all custom posts (event), order them by custom field (date) and group by month: September * Event 1 * Event 2 August * Event 3 July * Event 4 * Event 5 I know, it is frequently asked question here, but despite the reading many similar issues, I can't do anything meaningful according them. So all posts are still ordered by default - by date of publishing. I will grateful for any hints. This is my code: <?php $args = array( 'post_type'=>'event', 'posts_per_page'=> -1, 'order'=> 'DESC', 'orderby'=> 'meta_value', 'meta_key'=>'event_start_date' ) $events = new WP_Query( $args ); if ($events->have_posts()) : while (have_posts()) : the_post(); the_title(); // (etc.) endwhile; endif; ?>
<?php $period = date("Y-m-d"); $args = array( 'post_type'=>'event', 'posts_per_page'=> -1, 'order'=> 'DESC', 'orderby'=> 'meta_value', 'meta_key'=>'event_start_date' 'meta_value' => $period, ) $events = new WP_Query( $args ); if ($events->have_posts()) : while (have_posts()) : the_post(); the_title(); // (etc.) endwhile; endif; ?> Please follow below link for details. Link for details link for code source Thanks!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, loop, date" }
Adjust Price Display for Variable Product in Woocommerce I want to adjust the price display for a variable product so that instead displaying as something like "$10.00-$12.00" it will display as "$10.00 or $12.00" -- essentially replacing the ndash with an "or". How would I go about doing this?
You can hook into `woocommerce_variable_price_html` and reformat the price to include or. This will replace the `&ndash;` with `or` on all products with multiple differing prices. add_filter('woocommerce_variable_price_html', 'custom_variation_price_seperator', 10, 2); function custom_variation_price_seperator( $price, $product ) { $price = ''; $prices = $product->get_variation_prices( true ); $min_price = current( $prices['price'] ); $max_price = end( $prices['price'] ); if ( !$product->min_variation_price || $product->min_variation_price !== $product->max_variation_price ) { $price = $min_price !== $max_price ? sprintf( _x( '%1$s <span class="or">or</span> %2$s', 'Price range: from-to', 'woocommerce' ), wc_price( $min_price ), wc_price( $max_price ) ) : wc_price( $min_price ); } return $price; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic, e commerce" }
How to call wordpress custom post type page i make a custom post type in WordPress and i also make its separate two pages single-acme_product.php, archive-acme_product.php but the issue is when i upload the post from custom post type its show index.php here is my code of function function new_post_type_wp(){ register_post_type('acme_product', array( 'labels' => array( 'name' => __('Products'), 'singular_name' => __('Product') ), 'public' => true, 'has_archive' => true, ) ); } add_action('init','new_post_type_wp'); please tell me how to i navigate my custom post to specific custom page i also read wordpress codex its very help full i follow its method but my issue is same kindly help me reference link : <
Since WordPress is having trouble recognizing your custom template files, you could use this instead. Insert into your `single.php` file. Based on your description above, it sounds like you don't have a `single.php` file so you will likely have to create one. If you do already have a `single.php` file then there is likely still some confusion with your exact problem because a custom post would only display the `index.php` template if there was no `single.php`. Or you could just be confusing the two. <?php if( get_post_type == 'acme_product' ) { // Put the template code to display the custom post type post } else { // Code for all other posts } ?> This will work in any of the default WordPress post related template files like categories, archives, etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts" }
How to get home page ID? I'm building a Wordpress plugin in which I need to get the **HOME page ID value**. Do you know how can I get it? I know that we can get the current ID with `the_ID()` or `get_the_ID()` function, but I need specificly the **HOME page ID value**. My plugin is located at the following directory path: wp-content/plugins/myPlugin/
`$pageID = get_option('page_on_front');` should get you the Page ID of the page set at 'Front Page' in WordPress options.
stackexchange-wordpress
{ "answer_score": 28, "question_score": 10, "tags": "plugins, homepage, id" }
How to restrict wp-admin and prevent upload errors I need to restrict wp-admin access to all users who cant manage_options and still let users add media on the front end. function wpse_11244_restrict_admin() { if ( ! current_user_can( 'manage_options' ) && $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) { wp_redirect( home_url() ); } } add_action( 'admin_init', 'wpse_11244_restrict_admin', 1 ); I found this code on stack overflow and it works great for my disabling the backend. The only hiccup I have found is when I go to add media on a front end post I get the following error. ![media upload error]( When I refresh the page and click add media I now see the image that showed the upload error. ![enter image description here]( The image does upload but the only way the user would know that is if they refreshed. How can I disable backend access for everything and still allow them to upload media?
You just need one extra thing for this. Here is the code I typically use to do what you are doing: function pws_block_admin() { if ( // Look for the presence of /wp-admin/ in the url stripos($_SERVER['REQUEST_URI'],'/wp-admin/') !== false && // Allow calls to async-upload.php stripos($_SERVER['REQUEST_URI'],'async-upload.php') === false && // Allow calls to admin-ajax.php stripos($_SERVER['REQUEST_URI'],'admin-ajax.php') === false ) { if ( !current_user_can('manage_options') ) { $redirect_to = home_url(); wp_redirect($redirect_to, 302); } } } add_action('admin_init', 'pws_block_admin', 0); It looks like you are just missing the exclusion for allowing async-upload.php to work.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "admin, uploads, media" }
Wordpress The Next Posts So for previous and next posts I used this from wordpress codex <div class="navigation"> <p> <?php posts_nav_link('&#8734;','Go Forward In Time','Go Back in Time'); ?> </p> </div> I want to change that.. in the wp-admin, I used on settings -> reading -> Blog pages show at most = 5 so I wanted to have a button to click on and load like 5 more posts, every time you click on the button and you are on the bottom of the page ... to give you an example cuz my english is not that good.. < at first you see the some posts and if you scroll down, you click on a button and it loads more posts.. is that somehow possible to load the posts on the same page?
I found a tutorial about infinite scroll - < Maybe it will help you too. you need JetPack as plugin to do it! :) Worked for me fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, previous, next" }
Faster fonts on mobile I think I have a great idea to make my site load faster in mobile: _"don't load the custom fonts in small screens"_ I know how to style/change the font used depending on screen size with media queries and css. What I don't know is how to prevent the custom fonts from loading in small screens. I use google fonts and I enqueue them in functions.php, but I'm open to your workarounds. Btw, this how to do it, when using @font
WordPress has `wp_is_mobile()` function to detect mobile and handheld devices. You can use that to define your enqueue function to load fonts conditionally. You can enqueue fonts for non mobile devices like this. function my_enqueue_function() { if ( !wp_is_mobile() ) { wp_enqueue_style( 'gfonts', ' false, NULL, 'all' ); } } add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, wp enqueue style, responsive" }
How can I remove clutter from my page? I have much clutter on my page: * a search field with capital letters and centered: * latest posts * latest comments * archive * categories * meta with smaller and small letters: * home page administration * logout * RSS (post) * RSS (comment) * WordPress.org and * Proudly powered by WordPress | Theme: Argent by Automattic On a blog site they would be useful but this is a page for a small business. I do not want any of this. What is a standard and elegant way to remove these from my pages?
That clutter is part of the default content added with WordPress and theme installed. You can remove it through the Admin Dashboard UI: Since you are using the `Argent` theme by Automattic, you need to go to `Appearance` -> `Widgets` -> `Footer Widget Section` and drag all the unnecessary widgets out from it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "design" }
Which language files are loaded? Is there a way to print a list of the loaded language files for debugging reasons?
Thx to the comments I found the plugin: **Debug MO Translations** It returns a list of all searched and loaded MO files. The source code is provided on github: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "multi language, debug, language, wp debug" }
Get the path of the first attached media (single.php) I'm currently developing a wallpaper website using WordPress and I'm trying to figure it out how to retrieve the path of the first attached media in the post so I can display the path in the post (e.g., `/wp-content/uploads/image.png`). I tried a lot of WordPress functions such as `get_attached_media()` but I had no luck.
So I finally found out how to display the path of the first attached media in the post. Here is the code I inserted in **single.php** to display the path at the end of the content : <?php $image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); $path = parse_url($image_url[0], PHP_URL_PATH); echo /var/www/wordpress/wp-content/uploads$path; ?> Result (for exemple): /var/www/wordpress/wp-content/uploads/2015/12/image.jpg Hope it will help someone else!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "attachments, media, paths" }
Changing Image Size Settings does not show in Image Details I would like to change the image sizes for "medium" and "large". I did change the sizes in Settings > Media ![enter image description here]( This however does not seem to have any effect on the settings I see when I edit or insert an image: ![enter image description here]( I did empty cache and reset the browser. I also changed the theme's settings for the custom image size and content_width accordingly – but this does not have any influence on what options are displayed under _Image Details_. add_image_size('full-width', 1600, 0, false); if ( ! isset( $content_width ) ) $content_width = 1600; Now I'm stuck – would appreciate any pointer… Thanks! PS: I know there are plugins like Simple Image Sizes that could be handy – but I would like to try to do this 'the right way' (if that makes any sence).
Your image sizes need to be regenerated, as for the images to have different sizes they need to be cropped from the original and written to an actual file, whereas the settings only updates the settings, so will only affect future uploads. The Regenerate Thumbnails plugin can help with fixing this. The plugin allows you to regenerate the image sizes for all images or any number of specific individual images.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images" }
Wordpress lowers image quality I am uploading to my site large images with media uplader and I want them to have 100% quality but wordpress reduces the quality. What should I do or what plugin to install to prevent this?
WordPress by default compress and lower image quality. To disable it please enter this code in functions.php file of your theme. add_filter( 'jpeg_quality', create_function( '', 'return 100;' ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "media library, images" }
Set default number of columns in gallery Is there a way to set default number of columns in gallery? It is set to 3, and currently I change it manually for every gallery in post I create to 4. Here are the settings on the right < In codex they say "3 Columns is the default settings, which is ideal for most sites.", but not a word about how to change it. I have only found that I can add it to the shortcode ( [gallery columns="4"] ), but this isn't what I need
You can override many of the Gallery Settings using the `media_view_settings` filter: /** /* Gallery Default Settings /* @param Array $settings /* @return Array $settings */ function theme_gallery_defaults( $settings ) { $settings['galleryDefaults']['columns'] = 5; return $settings; } add_filter( 'media_view_settings', 'theme_gallery_defaults' ); To change more settings, the easiest way is to use Developer Tools to inspect the actual field. What you're looking for is an attribute called `data-setting`. Grab that value and use it to override the defaults. Of course it should be noted that this will not update galleries that already exist. You'll have to run a filter on `the_content` to change it on the fly. Credits: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "gallery" }
Unabled to Change Permalinks - Even Using the "Edit" (Resets to Original Permalink on "Update") I have tried everything in every post I have been able to find about changing permalinks for existing posts and pages. I have gone to settings and change the permalink structure in hopes that it would reset it. This had no effect on "Pages". If I change the title do "Page Title", then click the "Edit" for the permalink, and change it to "post-title", it will still not change it. It appears to work, but when I click "Update" it updates to the original permalink. Does anyone have a direction or solution at getting this to work?
Thank you TheDeadMedic, I should have tried this already, but here is the answer: I had the "Slug" Meta-box hidden, using the "remove_meta_box" function because it is annoying, especially for users that aren't tech-savvy. Unfortunately, Wordpress keeps the Permalink "Edit" as if you could edit it, but it is actually necessary for the "Slug" div to be on the page (even if it is hidden by "Screen Options"). Once I re-enabled the "Slug" div, it works again to change the permalinks.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, permalinks, pages, core" }
Showing author's page with no posts I'm building a meet the team page, which will be included all team members. I'm using the author.php file template. I have a page that shows all authors (it works with authors who have no posts). When clicked it redirects to the author page. There, everything works fine if the author has posts, but I want it to show all authors. As simple as outputing the author's name: `<?php the_author_meta('first_name') . ' ' . the_author_meta('last_name'); ?>` Only works if the author has posts. How can I display the author, even if he has not posts at all?
You can use the get_queried_object where the CODEX says: > if you're on an author archive, it will return the author object So since you have an object, you can return it values: $author = get_queried_object(); echo $author->first_name . ' ' . $author->last_name; And you can use the same parameters as get_the_author_meta(): user_login user_pass user_nicename user_email user_url user_registered user_activation_key user_status roles display_name nickname first_name last_name description (Biographical Info from the user's profile) jabber aim yim googleplus twitter user_level user_firstname user_lastname rich_editing comment_shortcuts admin_color plugins_per_page plugins_last_view ID
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "author, author template" }
CMB2 metabox conditional logic I am using CMB2 for metabox on custom posts. I am adding a metabox by using code below: $cmb_demo->add_field( array( 'name' => __( 'Test Text', 'cmb2' ), 'desc' => __( 'field description (optional)', 'cmb2' ), 'id' => $prefix . 'text', 'type' => 'text', 'show_on_cb' => 'show_this_field_if_true', ) ); I understand show_this_field_if_true will be a function that will return true or false. But, I want to make this as conditional with another field. This field will show if another field's value is true. Here is an example that Don't show this field if it's not the front page template function show_this_field_if_true( $cmb ) { if ( $cmb->object_id !== get_option( 'page_on_front' ) ) { return false; } return true; } How can I make this conditional with a field?
The best way to do this is by using JavaScript and there is a couple of CMB2 plugins let you do that easily: 1. CMB2 Conditional 2. CMB2 Conditional Logic
stackexchange-wordpress
{ "answer_score": 0, "question_score": 4, "tags": "metabox, plugins" }
Can an RSS item be altered with a hook? I would like to alter the content of each item in a site's RSS feed with a regular expression. The rss2_item hook is close but it is run just after the item has been output, so is only really useful for _adding_ data to a feed item, I need to _alter_ the item with a regex before output. Is there any way to do this with an `add_action` hook or do I need to create a whole new `rss.php` feed file?
the_content_feed is the hook I needed. In my case I am running a regex to replace relative URLs to absolute ones, so I added the following code to `functions.php` add_action('the_content_feed', 'relative_to_absolute_links'); function relative_to_absolute_links($content) { return preg_replace("/(src=['\"]){1}\/{1}([^\/][^'\"]+)(['\"])/im", "$1" . get_site_url() . "/$2$3", $content); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "hooks, rss, api, regex" }
All Images on wordpress site broken Recently one of my live wordpress site's broke. And no it was not because of an update since I haven't updated recently (only to 3.1 but then everything worked) For some reason all images now look like this: example.nl/index.php?aam_media=3470. And I cannot acces it. Also when uploading new images they also are instantly broken what could be the cause of this. Live version with image error: < Live other site with almost same setup & plugins but not broken: < So does anyone has any clues? I hope I have provided enough information, I can give additional information as needed. I have contacted support but so far no luck with them.
It's due to AAM (Advanced Access Manager) plugin. You have different options to fix the issue. 1) Disable AAM Media Manager plugin 2) You can changes AAM Media Manager plugin version 3) If you do not want AAM to handle your website images, Go to the following file /advanced-access-manager/extension/AAM_Media_Manager/extension.php and find private $_skip = false; change above to private $_skip = TRUE; Please refer this link for more details. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "images, uploads, links" }
wp_enqueue_style and different styles for blog template I have a `front-page.php` to create the index page template and a `page-blog.php` to create the blog template. My styles are added using `wp_enqueue_style` in my `functions.php`, but I'd like to use different items (css and js) on `page-blog.php`. Is it possible?
When using hooks such as `wp_enqueue_scripts` you have access to Conditional Tags. This allows you to only enqueue certain things on certain pages, templates, taxonomies, etc. By default, WordPress accepts two template files as the natural blog: 1. `index.php` 2. `home.php` You can read more about this in the Template Hierarchy post, while it does say "Home" this will only take the place of the homepage if `front-page.php` does not exist in your theme. What you have is a Page Template as your "Blog" and **not the standard** you need to use `is_page()`: /** * Enqueue Styles and Scripts */ function theme_name_scripts() { if( is_page( 'blog' ) ) { // Only add this style onto the Blog page. wp_enqueue_style( 'style-name', get_stylesheet_uri() ); } } add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "templates, page template, blog" }
Where are widget configurations stored? I did search and saw a similar Where (what directory) are the default Wordpress Widget Codes stored? but this is not my question. When I have a lot of widgets configured, say a few dozen RSS feeds each in its own widget, where exactly is this data stored? I'd like to be able to copy this data to import into another theme using the same plugin/widget without needing to retype all the urls fed into the rss widgets. Update - it seems this request is looking to solve an issue at the wrong level. Elsewhere, I was advised to just use a plugin, Widget Importer & Exporter and it preserved the widget settings very well. No need to mess with the source or SQL.
The widgets data is stored in `wp_options` table as serialized array, with `option_name` started by `widget_`: ![Widgets Data](
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "widgets" }
Add itemprop Schema.org Markup to li Elements in wp_nav_menu I currently call menus with a basic wp_nav_menu code: <?php wp_nav_menu( array('theme_location' => 'primary') ); ?> I am trying to find the easiest way to add `itemprop="url"` to the line elements for the purpose of Schema.org markup. However, all of the codes I have found seem overly complex. Any help is greatly appreciated. Is there a way to simply impact the line elements without impacting others menus?
To add attributes to the menu's li elements, you'd have to write your own custom walker that extends the default Walker_Nav_Menu class (which is itself an extension of the Walker class). For more info: < But as itemprop="url" should normally be added to anchor elements, you could use the nav_menu_link_attributes filter. For example, as per the WP docs, adding this to your functions.php will add the attribute itemprop="url" to your anchor elements within the list item elements of your menu: function add_menu_atts( $atts, $item, $args ) { $atts['itemprop'] = 'url'; return $atts; } add_filter( 'nav_menu_link_attributes', 'add_menu_atts', 10, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, functions, menus, html" }
$wp_customize->remove_section for customizer setting? I use an underscores theme and try to remove the nav menu without any result : $wp_customize->remove_section('colors'); // works $wp_customize->remove_section('background_image'); // ok $wp_customize->remove_section('header_image'); // ok $wp_customize->remove_section('static_front_page'); // ok $wp_customize->remove_panel('widgets'); // ok $wp_customize->remove_panel('menu_navs'); // not ok $wp_customize->remove_section('menu_navs'); // not ok What's wrong ?
Assuming you are trying to remove the default `nav_menus` panel, you have the id wrong. Also, you'll need to add a priority of at least 20 to the `customize_register` hook, assuming you're using that hook. function remove_customizer_settings( $wp_customize ){ $wp_customize->remove_panel('nav_menus'); } add_action( 'customize_register', 'remove_customizer_settings', 20 );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "customization, themes, admin menu" }
Adding schema to text content in the loop, how? Given the following code: <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'full', array( 'class'=>'post_thumbnail_common', 'alt' => get_the_title() , 'title' => get_the_title(), 'itemprop'=>'image' ) ); echo contentnoimg(41); } else { echo content(41); } ?> How can I add `<div itemscope itemtype=" before `contentnoimg()` and `</div>` after it? If I add it in the code, it breaks the syntax, because I can't use html in php code.
Just add them to `echo` <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'full', array( 'class'=>'post_thumbnail_common', 'alt' => get_the_title() , 'title' => get_the_title(), 'itemprop'=>'image' ) ); echo '<div itemscope itemtype=" } else { echo content(41); } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "the content" }
How to use theme function in post/page? I want to be able to reference the theme directory in a page/post using php code. I don't know how to do this with WordPress but other CMS use something like a `path_to_home` php variable like <img src="<?php path_to_home() . 'images/image.jpb'; ?>"> In WP I tried <img class="first-slide" src="<?php get_template_directory_uri() . '/images/landing-banner.png'; ?>" alt="First slide"> but that doesn't work the same way or I need something different than `get_template_directory_uri()`. BTW my output with this code is a literal <img class="first-slide" src="<?php get_template_directory_uri() . '/images/landing-banner.png'; ?>" alt="First slide">
Whenever using any WordPress function with get_xyz_etc() make sure you ECHO the function if you want to output the value there: <img class="first-slide" src="<?php echo get_template_directory_uri() . '/images/landing-banner.png'; ?>" alt="First slide"> It will now output the path!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, pages" }
WordPress API - count posts Is there a way to count the number of posts / pages via the WordPress API? I'm wanting to insert a post then check, using the API, that the count has gone up by 1. I've looked at <
Assuming you are using Linux or OS X, the easiest way is probably to use wp-cli (if present in your WordPress installation) to return a list of all posts: wp-cli post list Then pipe it to the word count tool to get the number of lines: wc -l Finally, deduct one to take care of the header line which is not a post: awk '{print $1-1}' So, in one line: wp-cli post list | wc -l | awk '{print $1-1}'
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "api, wp cli" }
How do I hook into the container of wp_nav_menu? I know I can edit the items within the wp_nav_menu by declaring a custom walker, but I want to add some code just inside the container, which isn't handled by a walker. It's in nav-menu-menu-template.php, so I can get the desired effect by adding my code after line 329... $nav_menu .= "<div class='topper'> <a href='".get_home_url()."' class='intranet'>H</a> </div>"; ...but of course this will disappear on an update. What hook do I need to achieve the same?
Solved it by setting `container` to `false` and then wrapping it manually. <nav class="main_navigation"> <div class="topper"> <a href="<?=get_home_url()?>" class="intranet">H</a> </div> <?php wp_nav_menu(array('container'=>false) ?> </nav>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, menus, hooks" }
Direct URL to a template via plugin I'm trying to create a "profile page" of sorts for users that I want to use the URL structure: `www.domain.com/profile/USERNAME` The system does **NOT** user the default WordPress users. I've not attempted this yet as I've got no idea where to start! I'd prefer it if this page wasn't a Wordpress "Page" and I'd like for it to be created via my plugin's `profile.php` file (That contains the `profile` class). The username is stored in the site's `SESSION` so it doesn't need any variables. I just need to link a URL to a template without using WordPress pages, really :P I'm not sure what information to provide so if there's something I've missed please let me know :)
This really isn't the best use for wordpress. You are better off creating a custom post type called "profile" (see < or use a plugin like PODS) and then the URL rewrites are all done for you. You can enable / disable the archive page so that domain.com/profile lists all profiles or not at all. Then add post meta (see < to your custom post type for extra fields you may want. I would recommend using ACF (Advanced Custom Fields) for this. ACF is a great tool for rapidly creating advanced meta fields for specific scenarios. In any case, don't waste your time custom cowboy-coding your own object when WordPress can do it already with alot less code. It's less work for you in the long-run.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, redirect" }
Admin mode breaks with subdomains in latest WP This is the symptom/issue - I am using a subdomain, and latest Wordpress Rev, as well as PHP on server. When signed in to my site as admin, if I choose admin/customize, I get a new signon screen within a frame and message "Session expired. Please log in again. You will not move away from this page." I've confirmed this error occurs regardless of theme. And WordPress Address (URL) & Site Address (URL) match. Last, for what it's worth, I've had this subdomain running for well over a year with no issues, it only shows this symptom recently. As if the Rev of WP were the issue. UPDATE - I backed up my data, and reinstalled from scratch. The problem is no longer appearing.
The issue could be with setting up cookie which may happen if you have different siteurl and homeurl. To give it a try, please edit your wp-config.php file and add these two: define( 'WP_HOME', 'abc.example.com/'); define( 'WP_SITEURL', 'abc.example.com/'); Please replace abc.example.com with your actual subdomain. The thing to make sure is both URLs should match. If above does not resolve, then one more thing you can try is setting your cookie domain to the subdomain define( 'COOKIE_DOMAIN', 'abc.example.com/');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin, subdomains" }
How to install seperate theme on certain page My question pertains to the latest version of WordPress. I am looking to have a two themes on under 1 domain. In other words www.abc.com will have one theme present. www.abc.com/about will have a completely separate theme.. Its the same concept as Wordpress Theme sites, they will have 10-30 different layouts, and are able to 'demo' each layout under the same domain. I am wanting to showcase different examples under 1 www.abc.com domain. If anyone can provide additional information, or even what I should be searching for (method definition) I would greatly appreciate it. tl;dr I have heard of subdomain, and subdirectory. I just want to be able to have a friend go to abc.com/example1 and abc.com/example2 to showcase different theme layouts for them, what is the best way to approach this? Thanks!
There exist two cases in your question. 1\. You want different theme for different pages of single WordPress site. You can achieve this using a plugin - Multiple Themes 2. You want different sites having different admin dashboard and different theme for each site. Then you must use MultiSite.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite" }
How do I transfer from a self hosted blog to WordPress.com? Normally, people move from WordPress.com to a self hosted blog. I want to move from a self hosted blog to WordPress.com. Is this possible? This may be off topic but since it involves going from self hosted I think it is relevant.
There is a guide here that shows how to transfer from self hosted to WordPress.com. Go to tools and export. Go to tools and import.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "wordpress.com hosting" }
How to display the modified post today I'm trying to figure it out how to display a post with modified/updated today. Sql is possible with **post_modified_gmt < 'datetoday'** but can't find the function for post_modified_gmt on wp_query. Any idea? Thank you. $args = array ( 'post_type' => array( 'post' ), 'post_status' => array( 'publish' ), 'category_name' => 'Airing' ); $query = new WP_Query( $args );
You can use the `date_query` part of `WP_Query`. Here's an example: $args = array ( 'post_type' => array( 'post' ), 'post_status' => array( 'publish' ), 'category_name' => 'airing', //<-- N.B. This is for a category slug! 'date_query' => array( array( 'column' => 'post_modified_gmt', 'after' => 'today', 'inclusive' => true ), ) ); $query = new WP_Query( $args ); This should give you `wp_posts.post_modified_gmt >= '2015-09-24 00:00:00'` in the generated SQL query, if today is _Sep 24. 2015_.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wp query" }
Dropdown menu's fighting with each other I'm sure there's a simple CSS answer to this that I'm not seeing :( < On my navigation menu if you hover over a sub menu item, and then slowly move your mouse to the right, it will switch to the next items sub menu. I don't want this to happen especially for the "services" dropdown, because it has a 3rd tier menu I can't even hover over. I've tried throwing z-index's on the sub menu, and all the items under the sub menu. Nothing I do seems to work, I'm stumped at this point.
The problem is that though your sub menu is set to `opacity: 0`, its still displaying, just transparent. So when you hover any area where a submenu is present, you're triggering `#access ul li:hover` which sets the opacity of the submenu with `#access ul li:hover > ul`. Try setting adding `visibility: hidden` to `#access ul ul`. Then add `visibility: visible` to `#access ul li:hover > ul`. This will allow you to keep the opacity transition.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, theme twenty ten" }
Background setting isn't applied to entire sidebar height I am working on this WP website and can't for the life of me get the entire height of the sidebar to take the background setting. The theme is a child of TwentyFourteen. Through FireFox's Inspect Element I can see my background-color setting on the #secondary div, which is the main container for the side nav area, but I can't figure out why it's not coloring the entire height of the page, nor how to get it so.
On the WordPress support forums, my question was answered with this code: @media screen and (min-width: 1008px) { .site:before { background-color: #ff0000; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, css" }
htaccess conflict between Wordpress and password protected subdirectory I have a wordpress install in the root directory but also have a directory called 'admin' which contains a PHP membership system. I couldn't initially access this directory as I kept getting a 404 on the Wordpress site but added: ErrorDocument 401 default in to the .htaccess file and the 'admin' folder then became accessable. The admin folder now needs to be password protected so I have given it a htaccess file of its own containing: AuthType Basic AuthName "restricted area" AuthUserFile xx.xxx.xxx.xx/public_html/admin/.htpasswd require valid-user but this now makes the 'admin' folder inaccessable again, is there something I need to put in either of the htaccess files to make this work or is there a different method of password protecting the admin folder without using htaccess? Thanks
I have found a response on a forum which suggests that the only way of acheiving this is to create a subdomain for the folder which is to be protected, this works fine. Regards
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "htaccess" }
Handle POST request sent from an external site for login? How do I send a `$_POST` request to my WordPress application from an external website, and handle it here? I want to send user credentials, along with additional login data, to perform an auto-login. 1. Do I need to define a new URL for handling the $_POST request? 2. Which action hook do I need to use for handling such a request?
1. Do I need to define a new URL for handling the $_POST request? No, you don't need to define new URL. 2. Which action hook do I need to use for handling such a request? You can use `init` hook. ## Sample code function my_theme_send_email() { if ( isset( $_POST['email-submission'] ) && '1' == $_POST['email-submission'] ) { // Send the email... } // end if } // end my_theme_send_email add_action( 'init', 'my_theme_send_email' ); Now you can call your website with POST required POST parameters. ## Update: ![Executed function on init method]( Executed function on init method ![my code]( my code
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "login, authentication, single sign on" }
Get all terms/slugs - used, not used & in hierarchical order I need to get all the slugs/terms - those that are used & those that are not. It's hierarchical (3-4 levels). How to get all (used & not used) terms/slugs in hierarchical order? This code returns 1. level slugs & ONLY other levels that ARE USED: $locations = get_terms('location', array( 'orderby' => 'slug', 'parent' => 0, 'hide_empty' => false) ); This code returns a mess - hierarchy is all off & it's a big mess: $locations = get_terms('location', array( 'orderby' => 'slug', 'hide_empty' => false) );
Try this. `$locations = get_terms( 'location', 'hide_empty=0&orderby=term_group' );` The codex says to avoid using `term_group` but it should be fine. It was never fully implementet but, according to others, its used quite often.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "slug, terms" }
Recommended location to set response headers? I'm looking to set an `Expires` response header for all page requests. I see the `doctype` in the theme's header.php file, so I'm guessing I could set it right before that line, but I'm wondering if there is a better or more appropriate/recommended place to do this? <?php /** File: /themes/[theme]/header.php * The header for our theme. * * Displays all of the <head> section and everything up till <div id="content"> * * @package goorin */ // Should I set the Expires header here? header('Expires: ' . gmdate($somedatetime) . ' GMT'); ?><!DOCTYPE html> <html <?php language_attributes(); ?>> <head> ......
There's a filter for that: function wpse_203745_wp_headers( $headers ) { $headers['Expires'] = gmdate( $somedate ) . ' GMT'; return $headers; } add_filter( 'wp_headers', 'wpse_203745_wp_headers' );
stackexchange-wordpress
{ "answer_score": 10, "question_score": 5, "tags": "headers" }
Ignore a more tag when using get_the_content() This is such a simple question it seems yet I can't find a definite answer on it. So how do you make `get_the_content()` obtain all the content of a post even if it has `<!--more-->` inside of the text which normally makes the function return after it has been used ?
I would just get the raw content from `$post->post_content`, strip the `<!--more-->` and then do whatever you need with the result. Just remember, `$post->post_content` and `get_the_content()` both return **unfiltered** text, if you need filtered content, simply apply the `the_content` filter to the result from those two results ## EXAMPLE inside the LOOP global $post; $unfiltered_content = str_replace( '<!--more-->', '', $post->post_content ); // If you need filtered content returned $filtered_content = apply_filters( 'the_content', $unfiltered_content ); // Output filtered content echo $filtered_content;
stackexchange-wordpress
{ "answer_score": 8, "question_score": 3, "tags": "read more" }
Show different Google Map markers for different post_meta values A lot of websites use it but suprisingly nobody tell us how to do it (right way). I have few ideas but Im not sure if this was the most efficient way - Im not very good with loops (under a year of experience in programming). Raw example: Have lots of `if` statements in `foreach` or `while` loop. // All this inside loop - I've already got while loop for my multiple markers global $post; $veggie_type = get_post_meta($post->ID, 'veggie_type', true); if($veggie_type == 'carrot') { icon = marker_url_1; } else if($veggie_type == 'beet') { icon = marker_url_2; } //etc like 10 if statements Could anyone give me an advice or example?
Meta seems like a fine place for storing this data. To make it more compact: $markers = array( 'carrot' => 'marker_url_1', 'beet' => 'marker_url_2', ); $icon = isset( $markers[ $veggie_type ] ) ? $markers[ $veggie_type ] : $markers[0]; Or if you are sure you have markers for each type and you can rename the marker files, go with $icon = 'marker_' . $veggie_type . '.png';// png format is better for small images
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, google maps" }
Mark menu item as current-menu-item for category I have some categories on my WP website. When users sees this categories and posts from them i want to mark one of menu items as active. How can i set one of my menu items to have class "current-menu-item" for this categories and posts?
I use this functions. First of all, you have to add some custom class to your menu item (allow class input in Screen options, it's not visible by default). function mark_menu_item_as_active($classes, $item) { if( in_array('my-custom-class',$classes) && ( is_category('my-category') /* OR ...*/ ) ) { $classes[] = 'current-menu-item'; } return $classes; } add_filter('nav_menu_css_class', 'mark_menu_item_as_active', 10, 2); This function iterates through all menu items, and you will find your target item with that custom menu class. Then you will check whatever conditions you have (is_category, ...), and add another class to its classes (`current-menu-item`, ...).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "posts, categories, theme development, menus, sub menu" }
Get All Pages as strings in array I try somehow to get array of pages names. I don't think it's possible in some default method from WP. <?php $args = array( 'authors' => '', 'child_of' => 0, 'date_format' => get_option('date_format'), 'depth' => 0, 'echo' => 0, 'exclude' => '', 'include' => '', 'link_after' => '', 'link_before' => '', 'post_type' => 'page', 'post_status' => 'publish', 'show_date' => '', 'sort_column' => 'menu_order, post_title', 'sort_order' => '', 'title_li' => __('Pages'), 'walker' => new Walker_Page ) ;?> $arr = wp_list_pages($args); print_r($arr); But this return LINK-s "< A >" tags ... Maybe in PHP I can in some way "transfrom" this links to string ? :)
Use `get_pages()` to fetch an array of page objects, then pass that result to `wp_list_pluck()` to extract an array of just page titles: $page_titles = wp_list_pluck( get_pages(), 'post_title' ); print_r( $page_titles );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, wp list pages" }
Strip HTML tags on custom code from the_content I"m making a custom RSS feed and need a way to strip HTML tags from a custom code that grabs the first paragraph from a post. This is what I'm using: <?php $paragraphAfter = 1; // shows image after paragraph 1 $paragraphsShow = 1; // shows first two paragraphs $content = apply_filters('the_content', get_the_content()); $content = explode("</p>", $content); $max = (count($content) < $paragraphsShow) ? count($content) : $paragraphsShow; for ($i = 0; $i < $max; $i++) { echo $content[$i] . "</p>"; if ($i == ($paragraphAfter-1)) { } } ?>
Following Mark Kaplun advice, I fixed my problem. Just wish there was a way to like a comment. <?php $paragraphAfter = 1; // shows image after paragraph 1 $paragraphsShow = 1; // shows first two paragraphs $content = apply_filters('the_content', get_the_content()); $content = explode('</p>', $content); $max = (count($content) < $paragraphsShow) ? count($content) : $paragraphsShow; for ($i = 0; $i < $max; $i++) { echo **strip_tags($content[$i])** . '</p>'; if ($i == ($paragraphAfter-1)) { } } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, rss, the content" }
Can I remove WooCommerce main content hook? <?php /** * woocommerce_before_main_content hook * * @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content) * @hooked woocommerce_breadcrumb - 20 */ //do_action( 'woocommerce_before_main_content' ); ?> For now, I'm just commenting it out to disable _before main content_ and _after main content_. Is it possible to do it without modifying the plugin files? <?php /** * woocommerce_after_main_content hook * * @hooked woocommerce_output_content_wrapper_end - 10 (outputs closing divs for the content) */ //do_action( 'woocommerce_after_main_content' ); ?>
remove_action('woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10,0); remove_action('woocommerce_before_main_content', 'woocommerce_breadcrumb', 20,0); remove_action('woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10,0); I hope it works for you =)
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "hooks, woocommerce offtopic" }
Can not login with correct username and password I can not access to Wordpress dashboard with correct username and password. If I give any wrong password it's not showing any error message for the wrong. When I press on Log in button then the same page is (wp-login page) appearing. I've tried by deleting browser caches, cookies and replaced the old wp-login.php file with a fresh wp-login.php file. But it's still not working. If I reinstall the Wordpress on the domain the same trouble is appearing. I don't know where is the main problem for that. How can I solve this problem.
I've tried many methods but anyone couldn't worked for me. So tried to solve by myself. I've discovered a solution. First, I cleared Browsing Data (cookie, cache and others) by pressing Ctrl+Shift+Delete. Secondly, Exit from the browser. Third Step, Disconnect the internet connection. Fourth Step, Clean my PC using a cleaner software (I used wise care 360). Sixth, Connect the internet and successfully access to Wordpress dashboard.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 5, "tags": "login, wp login form" }
Make archive page show up in search results? I'm trying to get the archive page of a category show up in the search results. I've developed the following setup. A category is a store, the archive page is the store's main page. Every store has posts which are there current commercials. The URL of an archive page is example.org/store-name I now want these URL's to show up when someone searches for the store name. At the moment it only shows the stores current commercials. I've looked at multiple plugins (incl. search everything) but I can't get it do to this specific thing. Hopefully someone can help me with this. Either a solution or a point of direction to create this functionality. Thanks in advance!
The issue is that an archive isn't a post, it's not something that can be shown in the loop. On your search results page, you'll have to add some code to search categories for a similar name. You can accomplish this with the generic `get_terms`. Pass the searched term as the `name__like` argument (or maybe `description__like` if you want to store more store-specific stuff that could show in a search). `get_query_var( 's' )` will give you the search term to pass.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "search, archives" }
Foreach loop inside foreach loop? I have a situation where only way seems to use loop inside a loop. **Is that a good idea?** Like everybody else, Im looking for the most optimized solution possible. **Situation:** * I need to assing different markers for each type (these are taxonomies). * Yes, these markers are markers on Google Map API. * My code below is inside while loop that gets all posts I need. * URL from code is then used in Google Map JS to assing marker image. **What I've got:** // Types $car_type = get_the_terms( $post->ID, 'car-type' ); foreach ( $car_type as $type ) { $type_slug = $type->slug; foreach ( $type_slug as $type_slug ) { $marker_image = ' . $type_slug . '.png'; } }
Your 2nd foreach loop is a bug. `$slug` is a string with a single value, and you cannot pass a string to a foreach loop. If you set debug to true, you will see an error message telling you just this. You can simply just do //Different markers for different types $car_type = get_the_terms( $post->ID, 'car-type' ); //Apparently it don't get the slug if it's not in foreach loop foreach ( $car_type as $type ) { $slug = $type->slug; $marker_image = ' . $slug . '.png'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, google maps" }
Duplicate "default" form with jQuery I have this code: // Add form jQuery('.add-form').click(function() { // "Copy" default form formGroup = jQuery('.form-item').html(); // "Paste" default form jQuery('#main-form').append('<div class="form-item row">'+formGroup+'</div>'); }); **Situation:** * There's a form by default * If you press the button, this code runs * It duplicates default form & place it under default form * If pressed again, it makes third form & places it under the second * etc **Problem:** I need to store default form to code somehow - problem is that I need the new form to be with empty fields & with original DOM (it might change when fields are filled in). **Question:** How to store default form in code (hidden or something), so that it would always load default one? Or is there a better way?
I don't know your html code, but here is how it will work. The idea is that you keep the original hidden elsewhere. HTML <button class="add-form">add form</button> <form id="main-form"> <div class="form-item row"> <input type="text" name="abc"> </div> </form> <div class="stay-hidden original-form-item"> <input type="text" name="abc"> </div> CSS .stay-hidden { display:none; } JS // Add form jQuery('.add-form').click(function() { // "Copy" default form formGroup = jQuery('.original-form-item').clone(); // "Paste" default form jQuery('#main-form').append('<div class="form-item row">'+ formGroup.html() +'</div>'); }); JSFiddle: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, forms" }
get_template_part() does not work if you call it when you are in a subfolder Say for example you have a directory like this: theme - subfolder - template.php content-job-listing.php If I try and call get_template_part like so `get_template_part('content', 'job-listing')` from the file template.php (note this is just a generic name not that actual name I'm using) it returns NULL. Similarly, if I use `get_template_part('../content', 'job-listing')` this also fails to return the template. However, the first one works fine if both are in the same directory. get_template_part() does not work if you call it when you are in a subfolder of a t
`get_template_part()` will work the same no matter where or how deep you are within your theme. It always includes relative to the theme (or child theme) root. So if you call the following from anywhere: get_template_part( 'content', 'job-listing' ); ... it will try to load (in order): 1. `child-theme/content-job-listing.php` 2. `parent-theme/content-job-listing.php` 3. `child-theme/content.php` 4. `parent-theme/content.php` To load parts that are in a subdirectory of your theme, just use the path in the first argument: get_template_part( 'path/to/file', 'optional-slug' );
stackexchange-wordpress
{ "answer_score": 11, "question_score": 4, "tags": "get template part" }
Is it safe to use WordPress generated classes? I'm currently customizing a theme in WordPress and was wondering if it's safe to use the WordPress generated classes in my CSS. For example, is it okay to use `.page-id-105`? Is there any chance that the ID could automatically be changed in the future by WordPress and then re-indexed?
Post ID Specific Classes are not reliable at all. The ID is based on _when_ the page was created ( in what order since IDs auto-increment ). If the user "accidently" permanently deletes the page and needs to recreate it the page will have a new ID and thus not use any of the predefined styles. The best bet would be to use a Custom Page Template so the user can assign it to a specific page. This is probably the most user-friendly method.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, html" }
Increase content area width in TwentyFourteen In this website I need to keep the left nav sidebar on the left side of the browser window and get the white content area to extend to the right side of the browser window. I spent a good two hours trying different CSS settings on div#main and all of its child divs but it was to no avail. Settings such as the div width, floating the divs to the right, etc. Nothing worked.
There's a bunch of other things you may want to also do, but in order to make it stretch to the full extent on the right, simply remove the max-width elements from .site and .site-header. So that's .site { ~~max-width: 1260px~~ ;} and .site-header { ~~max-width: 1260px~~ ;}
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, css, theme twenty fourteen" }
Where is wordpress redirecting wp-admin/admin/dashboard to wp-admin and how to turn it off I mean when we have subdirectory install and /wp-admin/ is not referencing to directory wp-admin, but wordpress stills redirects and not just for wp-admin slug but also for admin and dashboard and maybe some more? Where is this happening? It is not in rewrite rules? Is it hard coded? I don't want this behavior and i want to turn it off, but i want clean solution, nota check url and if slug is present than do my redirect. Edit: When you visit `example.com/login` you're redirected to the login page, and `example.com/dashboard` redirects to the admin area. How can I disable this behaviour or change the redirect location? I have my own login and dashboard interfaces and would like to use those instead
you can remove this functionality by adding this code in a plugin or theme `remove_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );` This will remove all of dashboar, login, admin so if you will want some of them to still be there you will have to write your own replacement function to `wp_redirect_admin_locations` and hook it after you removed the hook to the original
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, wp admin, rewrite rules" }
URL links consistent with menus? I'd like to have a URL links consistent with menus on the page. For example: * Menu1: * Submenu1 * item1 * item2 * Submenu2 * item3 * item4 * Menu2: * Submenu... * etc.. The corresponding links shoud be: * myweb.com/menu1/submenu1/item1 * myweb.com/menu1/submenu1/item1 * etc. However, the links are * myweb.com/item1 * myweb.com/item2 * etc. How can I fix this?
You need to create the hierarchy using page parents. Either use quick edit, or go through each page and set it's parent, so that you end up with: * Menu1 * Submenu1 (Menu1 is parent) * Item1 (Submenu1 is parent) ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, permalinks, links, sub menu" }
Wordpress Is Saving Original Image Only I have spent a few days wrestling with this issue. I have also searched for a similar question to no avail. When I upload a new image, The only file being created on the server is the original image. (I am checking the upload folder through FileZilla.) Then, when the image object is returned it has the same url for all image sizes. Eg `$image['sizes']['thumbnail']` is the same as `$image['sizes']['large']`. I've been draughted in to help on this project so I am not sure if a plugin is causing a conflict. Has anyone seen this behavior before or does anyone have ideas on how I can troubleshoot?
you must add add_theme_support( 'post-thumbnails' ); in `functions.php` in your theme you can also use `add_image_size` function to add custom size
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Is it normal for a scheduled post to say "Missed Schedule" There is a custom post type I am making called announcements. When I set it to a future publishing time, say at 8:00. It will say at 8:01 'Missed Schedule'. However after a little while I will refresh and it publishes. Is this expected behaviour?
In short, yes. When wp-cron is not triggered frequently enough it will miss scheduled publish times. The behavior you mentioned above is normal. A visit to your site will automatically trigger wp-cron in the background and any "Missed Schedule" posts will be published promptly. To get more consistent behavior from wp-cron I'd recommend setting up a CRON JOB on your web server to run wp-cron on a regularly scheduled interval (every 30 minutes, every hour, etc.) By doing this you are instructing wp-cron to maintain your scheduled tasks without relying on web traffic to trigger wp-cron for you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "publish, wp cron, scheduled posts" }
Pull in content from page defined as static front page I am trying to pull in `<?php the_content(); ?>` for the page I have defined as the static front page in WordPress's back-end but can't figure out how to target it and pull it in.
The id of the static front page saved as an option name `page_on_front`. You can get it as `$front_page_id = get_option('page_on_front');` Once you have it call `get_post_field()`. `$content = get_post_field('post_content', $front_page_id );`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "frontpage" }
Where do the favicons for Media Files come from I have uploaded some PDFs to the Media Library. I cannot find a way to set the browser favicon for the PDF media files. Where does WordPress get the favicon from? Is there anyway to control the PDF Media file favicon?
To summarize the discussion in the comments, the answer for the question as it is asked is that it is not possible. The web standards as they are right now do not have a facility to declare a favicon for PDF files, only for the whole domain via the favicon.ico file. You can try to hack around it by 1. set the favicon.ico at the root of the site to the icon you want to be associated with media files and use the wordpress 4.3 site icon feature to handle the icon for the html (which should have priority over the favicon.ico). 2. server the media files from a different domain (for example a subdomain of the main site) and set there a favicon.ico that you want to be associated with the media files.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 5, "tags": "uploads, media, media library, pdf, favicon" }
disable plugin in specific dynamic buddypress pages I am using Buddypress and multiple plugins. I want to disable a specific plugin on a specific dynamic BP page. How can I disable a plugin in a specific dynamic BP pages e.g. sitename.com/members/username/messages ? Thanks
There are two ways to solve this issue: 1) As mentioned above, Plugin Organizer is a popular plugin built to handle this sort of request. 2) Custom code, either in your theme or in the plugin itself. Knowing the inner workings of the plugin you are attempting to disable will be important if you decide to go the custom code route. Previous answers to this question: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "buddypress" }
Does Deactivating a Plugin Help Anything? Does deactivating a plugin help with any performance on your website? I mean is it worth deactivating plugins that you don't use constantly? Does uninstalling a plugin make any difference from deactivating a plugin?
**Yes** The overhead of a plugin sitting in your plugin folder is negligible, and would have an impact on the plugins page. The main area of optimisation here is the % of free space on your filesystem. Active plugins on the other hand can run queries, make remote requests, do expensive parsing, filesystem operations, and all manner of expensive, longwinded, slow operations. Not all plugins are expensive to run however. Hello Dolly is a simple plugin that does almost nothing, whereas a plugin that fetches RSS feeds and creates posts can be an expensive plugin when you give it a lot of feeds. If a plugin is expensive to run, deactivating it fixes that. A deactivated plugin is just a file sitting on the filesystem, not being executed. Is it worth getting rid of plugins you aren't using? So long as they're kept up to date, there's no reason to remove them, but I would recommend keeping the plugins installed to those you actively use as not all plugins are maintained
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, deactivated plugin" }
How can I give access to my plugin sections in admin? This is my first plugin using roles and capabilities. How can I give the "subscriber" users access to my plugin in the WP admin, or make a menu for just subscribers?
You can wrap the parts you want a subscriber to see by wrapping the code with: if ( current_user_can( 'read' ) ){ // the code you want the subscriber to see } You can checkout the role and capabilities here <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development" }
How to rename "Publish" metabox title in post screen I've looked everywhere trying to find how to **rename** the "Publish" metabox title in the WordPress backend post screen. There's help for every other metabox for changing titles and there's help for changing everything but the title for the Publish metabox. I'm sure it's simple but I'm just not getting close.
The best way would be to remove the meta box and then add it back in with your new title: function change_publish_meta_box() { remove_meta_box( 'submitdiv', 'post', 'side' ); add_meta_box( 'submitdiv', 'YOUR TITLE HERE', 'post_submit_meta_box', null, 'side', 'high' ); } add_action( 'add_meta_boxes_post', 'change_publish_meta_box' ); (Change `YOUR TITLE HERE` to whatever you want)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, functions, metabox, publish" }
How to make a field appear only if a post meta field has a defined value? I have a post meta field `registrazione_singolaono`that has 2 value: singolo_file piu_file If one of these value is selected (in every post the first or the latter must be used) i want to show another custom meta field. For example: if the value of the custom meta field is > singolo_file It should display: <?php if((get_post_meta( $post->ID, 'registrazione_multipla', true))) { ?> <?php echo get_post_meta( $post->ID, 'registrazione_multipla', true ); ?> <?php } ?> If it is: piu_file it should display another big piece of php functions. I searched both on the codex, on this site and on google without getting any understandable help. Thanks. Any help is appreciated
I would store the meta value in a variable, and use an if/elseif statement to determine what should be displayed, like so: $registrazione_singolaono = get_post_meta( $post->ID, 'registrazione_singolaono', true ); $registrazione_multipla = get_post_meta( $post->ID, 'registrazione_multipla', true ); if ( 'singolo_file' == $registrazione_singolaono && ! empty( $registrazione_multipla ) ) { echo $registrazione_multipla; } elseif ( 'piu_file' == $registrazione_multipla ) { // something else }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, php" }
Categories overview that links to page displaying posts **I am trying to achieve the following** A page that displays a series of categories with a title, description and an image When a category is clicked, all posts that belongs to that category gets shown. **I see 2 ways to achieve this:** I could create a custom taxonomy, ad an image field and list all the categories in this taxonomy in a custom template. How to handle the templating for displaying the posts when a category is clicked, I am not sure of. I could create a template with categories registered and saved with wp_option, then from each post choose a category, then make a custom query to select all posts in that category. Again I am not sure which type of template to create. **_What is the correct way to achieve this?_**
There is no need to create a custom taxonomy or custom template. When we click on any category then wordpress by default called archive.php file which has code for display posts related to that particular category. So first use this code in any of your php template file to display category lists: <?php $args = array( 'orderby' => 'name', 'order' => 'ASC' ); echo '<ul>'; $categories = get_categories($args); foreach($categories as $category) { echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . $category->name . '" ' . '>' . $category->name.'</a></li>'; } echo '</ul>'; ?> Which display category titles, likewise you also can display category descriptions and images. And when you click on the category title, then it will call wordpress archive.php file which display posts related to that particular categoty.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories, custom taxonomy, templates, template hierarchy" }
How to fix On "An unexpected error occurred" message when I click on Add new theme or plugin? I am using hostgator hosting services. in every install of wordpress I get the below error message. "An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums." Any body have ideas that how to fix it ? I searched on many solution and applied that but no one will work for me yet.
You can resolve this error by following ways: 1. Check the hosting panel for blocked ports 2. Contact the Hostgator hosting support - They also inform you regarding the same of blocked port. On Hostgator shared plan, if your server has suspicious/malicious files on your server then they are blocking the ports. Some of my contacts faced same issue due to malicious files on their website.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, themes" }
What Are the Advantages of Using an mu-plugin What is the advantage of putting code in a mu-plugin as appose to a plugin or child theme? What is the proper usage for the mu-plugin? I mean I can just put code in my child theme but is that the proper usage? Thanks
Usually putting code in child themes means putting everything in the /functions folder. If you don't write alot of custom code this shouldn't be such a problem. By using mu-plugins you can create a more logical way or organising your code. Especially on larger websites this will make your life a lot easier. When new devs join the project, they'll actually know where to look for code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, themes, child theme, mu plugins" }
Multisite 404 page I've recently installed Multisite using sub directories and I was wondering if it was possible for the sub directory sites to have their own 404 page? Currently, any links coming in to the sub directory site that should return a 404 are returning a soft 404 on the main or root site. **EDIT** Thanks to Paul H for his suggestion below. I've created 2 new 404 templates with my 404.php template containing the simple if statement below: $current_blog = get_current_blog_id(); if ($current_blog == 2) { get_template_part('404', 'subdirectorysite'); } else { get_template_part('404', 'main'); }
The easiest way is to check for `get_current_blog_id();` and adjust your 404 template based on the current blog id. An other option is creating a child theme for every site and adding different page-404 templates.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, 404 error" }
Hash user emails in database? I have a wordpress based website, a very important thing is that no one should get to know the email addresses of the people who will admin. I will make the whole website private but I am still thinking what else could I do. So I got the idea I could hash the emails in the db. Has anyone done that? What are the functionalities that need email address? As far as I know it is only needed when creating the user, because the password is sent to the user, and then it is needed at a password reset. So I would need to modify these so that it decrypts the email first. Is there anything else? Do you think it's useless as a security measure?
Hashing is a one-way function, meaning you can't get back an original string from a hash value. You could use the PHP function `mcrypt_encrypt` to "encrypt" the email address and `mcrypt_decrypt` to convert it back. If you went that route, you could hook into `password_reset` to decode the email address before the password reset is sent, and then hook into `password_reset_after` to encode it again after.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, users, security" }
get_users() timeout on big userbase -- options to divide query? We run a daily cron that gets **all** the users' data and updates their values. The problem is that get_users() is timing out because of the big userbase. Yes, I can update the `php.ini` file and increase the timeout limit, but it would only delay the inevitable. So, potential solution is to `get_users()` in batches. For example, on the first batch, we get the users with ID 1-1000. Is the best approach to use the `include` parameter and list 1-1000 IDs in an array? Seems quite desperate. What other options are there for scenarios like these?
You are on the right track with the batch idea. You'll need a combination of parameters in your get_users() call. A combination of the "number" and "offset" parameters should get you what you need. In the example below $count is a reference to the batch that's currently running. <?php // inside a loop where $count is the number of times the loop has run $args = array( 'number' => 1000, 'offset' => $count * 1000, ); get_users($args) ?> UPDATE: $count would start at 0. The first time through the loop you'd get a set of 1000 users starting from the first user in the database because 0 * 1000 = 0 (no offset) The second time through the loop you'd get another set of 1000 users starting from the 1001st user in the database because 1 * 1000 = 1000 (i.e. skip the first 1000 results and retrieve the next set) Your loop should continue for as long as you have results being returned.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "users" }
Get category fixed in dropdown browse categories I tried to get categories directly from phpmyadmin, but i can't. then i tried to create this php scrip in public_html include "wp-includes/category-template.php"; $args = array( 'hide_empty' => 0, 'pad_counts' => true ); $categories = get_categories( $args ); foreach($categories as $category) { if($category->count == 0) { echo $category->name."<br />"; } else { // do nothing } } ?> but it's return Fatal error: Call to undefined function get_categories() in /mnt/env/*****/development/public_html/test.php on line 9
Is there a specific reason you're trying to do this outside of WordPress the normal way? If there is, you could do `include('wp-load.php')` to access WordPress functions. But that would only be if you _have to_ access WordPress externally. Normally your code would either go into your theme's `functions.php` file, or you would add your code to a custom plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, dropdown, phpmyadmin" }
remove/hide wp-editor I have created a meta-box for a certain page_template. So if the adminpage is loaded with the template it shows the metabox. This does not require the wp-editor to add content. So I would like to hide or disable it. I have searched the interwebs but they all came up with the disablement of the viaual editor or the html editor. Anybody any ideas to do this with a function or some CSS? M.
I believe the helper you're looking for (assuming we're not dealing with a custom post type) is: <?php remove_post_type_support('page', 'editor'); ?> When dealing with a custom post type you can exclude 'editor' from the 'supports' parameter to initialize the post type without the editor window. Finally, if you are trying to disable the editor only when a specific page template is selected from the "Template" drop down menu, your best bet is likely a Javascript/jQuery approach to HIDE "#postdivrich" after an onChange event is triggered by "#page_template". Just remember to SHOW when the other templates that do support the editor are selected.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, filters, css, wp editor" }
htaccess and redirect to new url using regex I have a hard time to create rewrite rule for a redirect using part of an old URL for WP. Example: Old URL: < or < New URL: < New URL should to have only dates and first three elements of a permalink after stripping from dashes. If I will remove part with replacing underscores to dashes all the rest works as should. Here are my .httaccess rules <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / #replace underscores with dashes RewriteRule ^(/news/.*/[^/]*?)_([^/]*?_[^/]*)$ $1-$2 [N] RewriteRule ^(/news/.*/[^/]*?)_([^/_]*)$ $1-$2 [R=301] #redirect to new URL RewriteRule ^news/index\.php/([^-]+-[^-]+-[^-]+).* /$1 [R=301,L,NC] #WP standard stuff RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>
Found that solution useful > I think, this is an expensive way to replace underscores with dashes. But this works at least in my test environment. The first rule replaces dashes one by one. The second rule then removes the prefix from the requested URL. RewriteBase / # replace underscores with dashes RewriteRule (.+?)_(.+) $1-$2 [R=302,L] # strip "news/index.php" RewriteRule ^news/index.php/(.*) /$1 [R=302,L]
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, htaccess, rewrite rules, mod rewrite" }
How to add programmatically all pages and children to backend menu I have a big website with tons of content, and I would like to automatically add all pages and their children to the menu in the backend, so I can then rearrange them easily via drag and drop. I tried to use plugins such as Auto Submenu but it doesn't work, and when I am using it I cannot add any pages manually, as soon as I save they disappear from the menu again. Is there a code I could use in the database to add all pages with their children?
The helpers you'll need are wp_create_nav_menu() and wp_update_nav_menu_item(). This will allow you to create a menu and then, using a query posts loop, programmatically add every page in your site dynamically. You can use the get_pages() helper to retrieve all pages from the DB. <?php // These are default args and don't need to be set explicitly. // I've included them here for reference. $args = array( 'hierarchical' => 1, 'post_type' => 'page', 'post_status' => 'publish' ); $pages = get_pages($args); // loop goes here // foreach or while will work, whatever you are comfortable with ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "menus" }
how many rupee or dollar charge to client to make theme I have a client they saying, make theme for me, i will sell it in the online market, i agreed to make wordpress theme with plugin integration but i dont know how many amount to charge for theme, anyone knowhow many rupees or dollar can i charge to them.
Its depends on the time taken to complete the project plus complexity. You can charge on hourly basis like 20 USD per hour. Some times project has more value than you charge, like you said that client wants to sell the theme on marketplace, so in that case you should charge more because he will need your support until the product on marketplace. Don't be greedy but don't afraid to charge more.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "plugin development, theme development" }
PM PRO addon package check user access to a specific post I have pmpro addon package installed and need to check whether user has access to post and then display text depending on that. Here's the code function members_only() { if( is_user_logged_in() ) { $user_id = get_current_user_id(); $post_id[]=array(361,369,367,371,476); if( pmproap_hasAccess($user_id, $post_id[0]) ) { ?> <style> .pricing-button { display:none; } </style> <?php } } } add_action('wp_head','members_only'); But not functioning, no error as well. Thank in advance for any help.
Got the answer figured out,dont know exactly what was wrong but just entered the ID( i.e 376) in each section instead of $post_id[0] array. Would be glad to know if something was wrong in the code I posted in my question. Thanks **EDIT** Was using $post_id[] = array(361,369,367,371,476); instead of $post_id = array(361,369,367,371,476);
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins" }
Decide Metabox Configurations for All Users How can I decide the metabox configurations for all the users on my website? Specifically the Dashboard metaboxes I want to make a default configuration for. Is this possible?
Metabox configuration is stored in the user meta, there are several of them so best way to find all out is to look at the ajax handlers code in \wp-admin\include\ajax-actions.php, therefor you should be able to set it up at user creation time to whatever value you want.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "metabox" }
Remove 'style=' from Tag Cloud I am attempting to style the widget tag cloud, however, it seems WordPress now adds `style="font-size: 8pt;"` automatically to the tag cloud class. Does anybody know how to remove this? Seems like a poor coding decision...
`wp_generate_tag_cloud` has a filter that allows you to edit the string input. You can use regex to find and remove the inline style: add_filter('wp_generate_tag_cloud', 'na_tag_cloud',10,1); function na_tag_cloud($string){ return preg_replace("/style='font-size:.+pt;'/", '', $string); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "tags" }
Wordpress updates being blocked by proxy my network proxy (I assume) is blocking my local wordpress installs to updating plugins and the core. Does anyone know how the update works and what would need to ask IT to whitelisted to allow updates to be done?
_WP_HTTP_Proxy ()_ adds proxy support for http API. You can ask for the info if you don't know already & put it into wp-config.php define('WP_PROXY_HOST', '192.168.x.x'); define('WP_PROXY_PORT', '8080'); define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org'); _Source:< If username & password is mandatory then, add these lines too `define('WP_PROXY_USERNAME', '_username_'); define('WP_PROXY_PASSWORD', 'xxxxxxxxx');`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "updates, proxy" }
Hide admin bar on certain post type I've got a custom post type - ID `productpopup`\- which I want to hide the admin bar for all users _including admin_. The theory behind my function is as follows: The post type is selected using get_post_type( $post ) == 'productpopup' And then the Admin Bar is hidden using add_filter( 'show_admin_bar', '__return_false' ); So putting the following in my themes `functions.php` in my mind should work, but it doesn't if ( get_post_type( $post ) == 'productpopup' ) add_filter( 'show_admin_bar', '__return_false' ); Wordpress 4.3.1
Don't hack your Wordpress core. It's overriden after every upgrade (plugins do exist for some reason). You can solve your problem in this way: 1) Open your `single.php`. 2) Define <?php function hideAdminBar ($post_id) { if (get_post_type ($post_id) == 'post') { add_filter ('show_admin_bar', '__return_false'); /* For removing the top blank space. */ echo '<style type="text/css" media="screen"> html { margin-top: 0px !important; } * html body { margin-top: 0px !important; } </style>'; } } ?> 3) Inside The Loop, call this function right after the `while` condition. Like this: <?php while ( have_posts() ) : the_post();?> <?php hideAdminBar (get_the_ID ()); ?> /* etc. */ <?php endwhile; ?> Hope this solves your issue.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "custom post types, admin bar" }
How do I turn a 404 page into an automatic search with the info from the url? All 404 implementations seem to revolve around showing related content. I think we can do one better by automatically searching for the missing post... How can this be done?
This can be done in two easy steps. 1. Upgrade your site search with a plug in, such as Relevanssi (optional). 2. Add the following code in functions.php or via Code Snippets (thx to @Howdy_McGee and Russell Jamieson for ideas!) function wpse_204310() { global $wp_query; if( is_404() && !is_robots() && !is_feed() && !is_trackback() ) { $uri = $_SERVER['REQUEST_URI']; $clean = str_replace( "/", "%20", $uri ); $clean2 = str_replace( "-", "%20", $clean ); wp_redirect( home_url( "/?s={$clean2}" ) ); exit(); } } add_action( 'template_redirect', 'wpse_204310' ); That's it. This code will parse the url for the blog title, and pass it along to your search page. All transparent to the user. This assumes a simple permalink structure, such as domain.com/post-title
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "genesis theme framework" }
Jetpack: Display Site Title when no Site Logo How do I use an if else statement to display site title if no site logo is selected in the customizer when using jetpack? I have php code written but it's not working. I think it's because `function_exists('jetpack_the_site_logo')` checks to see if jet pack is activated, not whether the Site Logo section contains an image: `<?php if (function_exists('jetpack_the_site_logo')) : ?> <?php jetpack_the_site_logo(); ?> <?php else : ?> <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> <?php endif; ?>`
According to this the `jetpack_has_site_logo();` is what I need to accomplish this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, conditional content, plugin jetpack" }
Plugin Translation project not found Today I go to our plugin page in WordPress.org and see the translation part under the support forum part. !translation However, when I click to translate this plugin, it displays "Not found". !not found I joined the translate.wordpress.org page, but I cannot find my project. How can I add my plugin into WordPress translation. We used to use Transifex project for our user to contribute their translate, we would prefer use WordPress translate cos it will be more easier for users.
Translating WordPress plugins is an experimental project. Not all plugins listed in the repo are available yet. Quoting the translating WordPress page, > The project currently contains only a couple of experimental plugins for translation.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, translation" }
Update post meta using pending_to_publish hook Below is my code for updating post meta. function changePostExpireDatetime( $post ){ $featurePlanID = get_post_meta($post->ID, 'post_price_plan_id', true ); remove_action('pending_to_publish', 'changePostExpireDatetime', 10, 1); $plan_price = get_post_meta($featurePlanID, 'plan_price', true); update_post_meta($post->ID, 'post_plan_price', $plan_price ); update_post_meta($post->ID, 'featured_post', "1" ); add_action('pending_to_publish', 'changePostExpireDatetime', 10, 1); } add_action('pending_to_publish', 'changePostExpireDatetime', 10, 1); Function is called but meta is was not updated. How can I update post meta in that hook.
I tend to make use of the `transition_post_status` hook as it gives you so much control over what you need to do. Be sure to check out the link for all available status options. What I specially like that the `$post` object is also passed to the hook, so you can target a specific post type as well for one. You can try something like the following: ( _Just be sure to update the values to your own, I just used mine as example_ ) add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) { // Check if we are transitioning from pending to publish if ( $old_status == 'pending' && $new_status == 'publish' ) { // Check whether or not the meta_key exists already with our value if ( ! add_post_meta( $post->ID, 'post_views_count', 50, true ) ) { update_post_meta ( $post->ID, 'post_views_count', 50 ); } } }, 10, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "hooks, post meta" }
Can i add wordpress editor to my custom theme option? I want to add wordpress default editor to my custom theme option editor, recently i have used textarea but this doesn't support for html format ! // Start Booking Section array( 'type' => 'textarea', 'name' => 'booking', 'label' => __('Booking Code !', 'machan'), 'description' => __('Add Booking Code for front-end display !', 'machan'), 'default' => '', ), // End Booking Section I am using vafpress framework 2.0 for wordpress back-end theme option and metaboxes.
ok if you use vafpress framework as you say so you only have small change :) just use wpeditor instate of textarea :) array( 'type' => 'codeeditor', 'name' => 'booking', 'label' => __('Booking Code !', 'machan'), 'description' => __('Add Booking Code for front-end display !', 'machan'), 'mode' => 'html', ),
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, options" }
Current author archive in navigation menu I want logged-in user see her/his own author archive page link in top navigation menu,say (a link to a list of all her/his posts). What I achieved so far is this: function my_nav_menu_author_link( $menu ) { if( !is_user_logged_in() ){ return $menu; }else{ $link = get_author_posts_url( get_current_user_id() ); $author_archive_link = '<li>' . '<a href="' . $link . '" >' . __( 'My posts' ) . '</a>' . '</li>'; $menu = $menu . $author_archive_link; return $menu; } } add_filter( 'wp_nav_menu_items', 'my_nav_menu_author_link'); It works fine, but the problem is that this menu link does not get the `current_menu_item` class. How could I add this functionality, so that I would be able to style it when it goes active?
Finally I figured it out and I am posting the solution for anyone who may be interested in such a workaround: function my_nav_menu_author_link( $menu ) { if( !is_user_logged_in() ){ return $menu; } else { $link = get_author_posts_url( get_current_user_id() ); $class = is_author() ? ' class="current-menu-item"' : ''; $author_archive_link = '<li' . $class . '>' . '<a href="' . $link . '" >' . __( 'My posts' ) . '</a>' . '</li>'; $menu = $menu . $author_archive_link; return $menu; } } add_filter( 'wp_nav_menu_items', 'my_nav_menu_author_link' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, archives, navigation, author template" }
How to display footer menus in wordpress I have an question. I've been registered footer menus from the following function. // Register Navigation Menus register_nav_menus( array( 'footer_menu' => 'Footer Menus', ) ); but can i know how to show this on footer
You have to register the menu, as you have done, and then use the function `wp_nav_menu()` in the template file where you want to display the menu. wp_nav_menu( array( 'theme_location' => 'footer_menu', ));
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "themes" }
get_post_types doesn't work in plugin The dilemma is that get_post_types() inside the plugin I am creating. And from researching now all post types are not registered until "wp_loaded". However, "wp_loaded" is executed when all plugins are loaded. All post types have yet to be registered, but I need them in my plugin. Is there a way to solve this problem? My custom post types are attached to init. class MyPlugin { public static function init() { self::load_plugin_textdomain(); self::register_post_status(); $pt = MyPlugin::get_post_types(); //add a column for each post type here //add_action and add_filter } private static function get_post_types() { return get_post_types( array( 'public' => true ), 'objects' ); } } add_action( 'init', create_function( '', 'return MyPlugin::init();' ) );
I don't think you’ll be able to get all the post types that are registered on init. (other plugins may register extra post types) Can't you hook into wp_loaded?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugins, plugin development" }
Update Plugin Without Overwriting Custom Settings My plugin uses the code below that has uid="x" in it that requires the user to edit the plugin and set "x" to their user id, such as uid="420971". Whenever I release an update to the plugin and the user downloads it, the update overwrites this setting because the update has the generic u="x" in it. How can I save the user's personal uid and apply it to the updated plugin? add_filter('the_content', 'the_plugin'); function the_plugin($content) { global $add_the_script; $content_add_on = '<div class="ACME_STATS" uid="x"></div>'; $theContent = $content.$content_add_on; $add_the_script = true; return ($theContent); }
Store the uid in an option. Use the Settings API to create an admin page to manage the option.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, customization, the content, excerpt" }
Block IP Addresses using Code Is there a way (which I am sure there is) to block IP addresses using code. I want the code to be in PHP so that I can put it in my child themes function.php to use for block some IP addresses. Thanks
Place in your template's `index.php` the following piece of code: $deny = array("127.0.0.1", "88.88.88.88"); if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) { header("Location: die(); } And just change the addresses of `$deny` for the IP address or addresses you want to block.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "code, ip" }
Network not displaying all sites and users We have more than 10,000 users and blogs on our wordpress network. There are 2 problems: 1. admin blogs listing wp-admin/network/sites.php only displays 1 page, no pagination, not displaying all blogs list, not displaying blogs count. 2. admin users listing wp-admin/network/users.php only displays 1 page, no pagination, not displaying all users list, displaying users count (10113). Please advice how can we fix this.
When WordPress builds such a list, it runs a check against the function `wp_is_large_network()`. It sets a limit of 10000 for users and sites, and when you hit that limit, expensive database operations aren't executed anymore. There are two filters with the same name, so you can change the limit. Example: add_filter( 'wp_is_large_network', function( $state, $type, $count ) { if ( 'users' === $type ) return $count > 30000; if ( 'sites' === $count ) return $count > 20000; return $state; }, 10, 3 ) If you just want to turn off that restriction completely, use: add_filter( 'wp_is_large_network', '__return_false' ); Please make sure that your database can handle that!
stackexchange-wordpress
{ "answer_score": 9, "question_score": 6, "tags": "multisite, users" }
Is post ID number always incremental n+ I have one question. Will WordPress always assign new post post ID which is incremental n+? For example if I delete some posts, will WordPress use ID of deleted post for new post added in future?
Post ID is always incremental. There's no way the ID of a previous post is assigned to a new post. If a post is deleted, the ID of that post remains vacant forever.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "posts, id" }
Cannot set user passwords In the admin panel, if I go to "Users -> Your Profile" I don't have the inputs to set the password. I can only generate it, but I want to set it by hand. Is that some kind of bug, or was this intentionally removed from wordpress. ![enter image description here]( If I check html with firebug I can see that inputs are actually there, but they are hidden. EDIT: In some old wordpress installation that has not been updated I can still see inputs for password change. See this screenshot: ![enter image description here](
In the fairly recent past, WordPress changed how the password change works. It _looks_ as though you can't set your own password; but in fact you still can: Click on "Generate Password," and then, when the automatically generated gobbledygook password comes up, simply edit that field to type in your desired password.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "users, profiles, password" }
How do I change the user via SQL? I change a user via SQL in wordpress: SET @old_user='old_user'; SET @new_user='new_user'; UPDATE wp_users SET user_login = replace(user_login, @old_user, @new_user); UPDATE wp_users SET user_nicename = replace(user_nicename, @old_user, @new_user); UPDATE wp_usermeta SET meta_value = replace(meta_value, @old_user, @new_user); However, while posting a new one, the author is still the old one, for instace, > Posted on October 3, 2015 by **old_user**. I must ignore something, please guide me.
You probably haven't changed the display name, which is probably what is being displayed. "nicename" is used for the author's posts page url and not for display. UPDATE wp_users SET display_name = replace(display_name, @old_user, @new_user);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, mysql, author, user meta" }
Newbie: Multiple WP sites on Windwos 2012 IIS Newbie Question: I have a Windows 2012 server with an existing ASP.NET / HTTPS site on it running a small SQL Server as well. My customer wants to add a dozen or so WordPress sites, one for each of its States. They must be independent with separate logins, separate sites etc, but the backend data store can be the same if need be. Is this possible without damaging the existing ASP.NET site? I've been reading on it, but it seems that I could damage the site installing WP?
Have you look at Wordpress Multisites? It should run if your current site is already running on ASP < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "iis, windows" }
Plugin - read post into blank page I wonder if I could produce a blank page (not within theme) and write something to it - I need my custom page. I know about WP Ajax, but it's not that simple, cos I wanted to be able to get some data crossdomain (with PHP and regexp) but Im not sure with that. Simply: I want bypass the theme (and its design) and give a blank page with custom plugin output. (Would be nice to be able to use WP functions) **Is it possible, or I have to use WP Ajax?** Thank you * * * Edit1: I want to add something like post with it's permalink (following permalink structure), but without using theme - just blank page with data created by plugin I know about including WP into external PHP files. I dont want any external file - it should be working within plugin
you can do it with a page template, or if you have to do it from a plugin add a rewrite rule to set a specific url for the "page"
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "custom post types, plugins" }
How to do something when user profile rendereing? Im new with worpress. I have a site wp+buddypress. Now i want get a fields value in user profile and do something depend by this field value. I can get this value useing: $class = xprofile_get_field_data( ‘Field_Name’, $user_id ); But i can't found place where i gonna put my code. What method i need to modify, or maybe exist hook what i can use to create separate plugin? `UPDATE Some code` <?php function remove_xprofile_links() { global $current_user; get_currentuserinfo(); $user_id = $current_user->ID; $field = xprofile_get_field_data(3, $user_id); echo "<script>console.log( 'Debug Objects: " . $field . "' );</script>"; } add_action( 'bp_init', 'remove_xprofile_links' ); ?> I put some code in `bp-custom.php`. Now i know a field value. But still dont know how to hide fields. Any advises?
I'm not sure I understand your question correctly, but I give it a try... <?php function remove_xprofile_links() { global $current_user; get_currentuserinfo(); $user_id = $current_user->ID; $field = xprofile_get_field_data(3, $user_id); $class = 'normal-profile'; if ($field == '{whatever}') { $class ='hidden-profile'; } $html = '<div class="' .$class . '">' . $field . '</div>'; echo $html; ?> And in css you should have .hidden-profile {display:none;}
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, buddypress" }