INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to get the form code from the edit page of a specific post? On a site I'm working on, in the profile page - for example - I have to display the content from a few custom posts (additional details, location details, billing). And instead of having the user click Edit and change the page to the 'edit page' for that particular post and then come back to edit the next one, I'm trying to display the edit form for the posts in a lightbox. Up until now I am able to load the complete get_edit_post_link page into an iframe, that's basic but the drawback is that it includes the full page, header, footer and all which I don't need. And turning them off in CSS is not elegant at all. For the life of me, I cannot figure out how to get just the edit form from said page. That is, short of making a fopen to the edit page and getting the code from there, which is even worse than the CSS option IMO! Including the edit form code into a lightbox would be ideal!
You could use jQuery's `load()` function instead of an iframe: $('#target-div').load(' #section-to-show');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, forms, include, lightbox" }
How do I change the category permalink structure? I've been trying to figure this out for ages. Please help. I want my category pages to default to www.teacherdavid.co.uk/blog/category However my category pages default to www.teacherdavid.co.uk/categories **live example:** < I can access the category pages at www.teacherdavid.co.uk/blog/category however this is not the where you are taken to when select to view a category page in the side bar on my blog page for example: < I've tried to set the permalink structure for the category pages with no luck. I should probably mentioned that I've removed the word "category" from my permalink structure using a plugin and my current post permalink structure is /blog/%category%/%postname%/ I'd appreciate any help. Thanks!
In Admin panel, Under Settings -> Permalinks, you need to update Categtory Base as well. For example, using "blog" as your category base would make your category links like ` If you leave these blank the defaults will be used.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, permalinks" }
error 'The package could not be installed. No valid plugins were found.' I am getting this error from a small plugin I've created. > The package could not be installed. No valid plugins were found. Code: /** Plugin name : Live Page Counter **/ function live_page_counter(){ global $wpdb; $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" ); echo "<p>User count is {$user_count}</p>"; } add_shortcode('counterhit', 'live_page_counter'); I don't know where I am wrong. Thanks
try without spaces beetween `Plugin name` and `:` Plugin name: Live Page Counter
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin development" }
What are the Oembed Links For? My copy of WordPress outputs two `<link/>` tags in the header of (nearly?) every page. They look like this. <link rel="alternate" type="application/json+oembed" href=" /> <link rel="alternate" type="text/xml+oembed" href=" /> What are these oembed links for? Do they need to be here for WordPress to do things? Or are they here so other sites can better consume my content? What would be the consequences if I removed them?
Those are links for the wordpress "self" oEmbed. It provides the URLs needed to enable embeding the content of the wordpress site in other sites and they are resuired for oEmbed Discover You are right that they are for other sites to consume your content, and if you don't care about it, just remove it. IMHO it is noting bad by itself, but if you are dedicating time for some cleanup, you should probably clean them as well. <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 9, "tags": "json, oembed" }
Pros and cons of a custom page vs custom post type template file Within my current setup, WordPress 4.6.1, I see the flexibility of creating a custom page and also a custom post type template file. I do a lot of custom web page development and build pages for a living. But I want to be efficient with my time and energy when working in WordPress, and would like to know when would it be appropriate to use one over the other? What are some basic pros and cons? i.e. * is one approach more powerful for data handling than the other? * is one easier to manage with style sheet usage than the other? * is one more flexible for WordPress api coding than the other? Thanks
The main difference is semantical. A page is something that stands by itself, while a post type in a categorization of content. This semantical difference results in different admin flow for both. The only other difference is that pages can have flexible URLs and you can basically put a page anywhere. As far as core API goes, you can do everything in any of them. So to answer your question directly, when to use one over the other depends on how you think the admin will use it. For example for most sites there is only one contact page, using a CPT for that will just clutter the admin UI. OTOH plugins that enable you to create many forms will use a CPT as it is results in a more organized admin for them
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom post types, pages, api" }
Seo Problems in My meta Discription Hi there guys i wanted to know how to fix this thing that is messing up with my SEO Meta description This is my homepage ![This is my homepage](
What you are seeing there is the shortcodes for your theme. You are likely using a theme builder which is why there are so many shortcodes. In the back-end, they will show as they are not being executed until they hit the front-end. You can see how shortcodes work with explanations here. In reality, they won't actually show up in search engines as by the time the search engine sees that page, the shortcodes will have executed and returned code/content. If you are really worried about it, what you can do is manually override that description by putting some content into the "Meta Description" box.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "plugins, shortcode, seo" }
Attribute Quote Style in WordPress HTML I've noticed that WordPress seems a little loosey goosey when it comes to quoting styles in the HTML it generates. Sometimes WordPress uses single quotes, other times it uses double quotes <link rel='next' title='An Example' href=' /> <link rel="canonical" href=" /> I know that single quote are, as of HTML5, technically "OK", but I'm weird and particular about how my HTML looks. Is there a way to tell WordPress to always use double quotes? If not, is there a plugin that might do this for me, or can someone point me to the appropriate do_action/apply_filter points so I can investigate this one my own?
First of all, either quotes are as good as each other. See this question There is no way you can do this with a plugin, action or filter. To achieve this you will have to do this manually by using the "find and replace" option on your IDE. I do not advise you to do this as: * You may end up breaking your WordPress core * You will lose all changes next time you will update your WordPress * You will have to go case by case as situations like these may appear: `echo <link rel='" . echo $bar . "' href="' . echo $foo . '";` in which case you will have to invert double quotes for single quotes and vice versa. This will be very time consuming for what you will get in return. As a matter of fact WordPress coding standards accept both quotation styles: See WordPress HTML Coding Standards on Quotes
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "html" }
Wordpress multisite proper prefix attribution I have installed a multisite network successfully using the sub-directory method. I created the first 3 blogs without a problem ( **prefix_2_ , prefix_3_** ) . I then needed to create a 4th one to test a functionality ( **prefix_4_** ). After testing the functionality I deleted the 4th blog (prefix_4_ ) and created another one to replace it. WP registered it as prefix_5_ . I deleted it again and recreated yet another testing one (prefix_6_ ). I am wondering how Wordpress determines we are at prefix_6_ and how I can reset that so that I don't jump from **prefix_3_** to **prefix_6_** in the database. Blog count shows 4 but Wordpress continues to increment the prefix numbe rregardless of how many blogs were deleted. Any explanation would be appreciated.
It is using a DB level "auto increment" flag on the base site `blogs` table. Basically, when a new record is inserted into the table the blog id number is automatically created with no discrete SQL -- it just "happens". The database keeps an internal control structure for this that you don't have direct access to. Even if you delete a row that internal counter does not change and the next insertion is simply +1 from the last one. Unless you turn off auto-increment for that primary key on the table, which would be a bad thing to do. See this answer for additional details. WP gets the new blog id from the insert_blog() call, which does not seem to allow the caller to specify a suggested or desired id number. You'd either need to write your own version of the functions that effect the instantiation of a new blog (not recommended), or try to live with this default behavior (recommended).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "multisite" }
Increasing the default number of posts in custom post types I need to increase the number of items I can show on my page using Custom Post Type and ACF plugin. Currently I have 26 items with tendency to grow, but it only shows 10 on my page. Here is part of the code: <?php $args = array( 'numberposts' => -1, 'post_type' => 'products', 'order' =>'ASC', ); ?>
I guess ACF is Advanced Custom Fields and CPT custom post type. I'm not used to these acronyms. Seeing -1 I guess you want to show all of your 26 items. change `numberposts` for `posts_per_page` <?php $args = array( 'posts_per_page' => -1, 'post_type' => 'products', 'order' =>'ASC', ); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, custom field" }
How do I change a Themes Header Image? I am having trouble locating the location of my theme's header.jpg so that I can upload and replace it with a new jpeg. The theme that is being used for my site is the "Flat-Theme" version 1.0 By the ShapeBootstrap team. When I go to "Pages" and edit my "Homepage" the header image is not present, it is also not in my site's "Media Library". Under "Page Attributes" my Homepage uses the "Frontpage" template. When I go to the appearance editor, specifically go to edit the "Flat Theme: Frontpage Page Template (page-frontpage.php)" I see that the theme references the header.jpg image in the coding for the header. If I am on my homepage, if I right click and "View Background Image" the URL shows up as: < I have been unable to locate how to change the header.jpg image for the URL above. Can someone please point me in the right direction!?
If your theme supports header images, it should be under Appearance > Header. No need to replace the old file, you can simply upload a new one. If this is not the case, you can change the reference to `header-new.jpg` in the editor, and upload your new header to the same folder via your ftp client. You could also replace the `header.jpg` file but then you would lose the default one. The recommended solution would be to create a child theme, but that's slightly more complicated.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, themes, uploads, media library" }
How to make current user's avatar + display name link to their profile? I have searched and searched, but not finding a solution to my situation. I have a certain page where the user's avatar and display name are displayed. Currently these items are not clickable and do not link to anything, however I need them to link to the user's member profile when clicked. Here is the code that is displaying the avatar + display name: $header .= "<div>".get_avatar($user_ID, 64)."</div>"; $header .= "<div><strong>".__("Welcome", 'front-end-pm')." ". fep_get_userdata( $user_ID, 'display_name', 'id') ."</strong>"; The first line is displaying the avatar, the second line is displaying the username. What needs to be done in order to make these items link to the user's profile page? (something like `www.example.com/members/user` would be the permalink location)
Use `get_the_author_link()` or `get_the_author_meta('user_url', $user_id)`. Your code would become something like: $author_link = get_the_author_link(); $header .= '<div><a href="'. $author_link . '">' .get_avatar($user_ID, 64).'</a></div>'; $header .= '<div><strong><a href="' . $author_link . '">' . __("", "front-end-pm").' '. fep_get_userdata($user_ID, 'display_name', 'id') .'</a></strong>'; Watch out with the quotes though, your code seems to use double quotes, I tried to replace it with single ones but you might have to check that in detail. If this doesn't work, use `$author_link = get_the_author_meta( 'user_url', 64 );` on the first line. This depends if you're inside the loop or not.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, links, profiles, avatar" }
Custom Post Type Trouble I made a Custom post type called CPT and most of it works fine. I made a 'single-CPT.php' file in the theme's folder to be the template for each CPT page. When I click on the permalink that I see while editing each CPT, the page loads using the 404 error template. I don't usually use the generated page so I don't know if I am doing this right, but I researched and found that Wordpress will locate the 'single-{custom post}.php' file in the theme folder and generate the page using that template. Why is my wordpress not doing that?
you likely need to do a flush re-write. go to settings/permalinks in the dashboard and click save. You'll be good to go. In the future you can add this directly to your CPT plugin. I would suggest getting a bit more creative with your naming though so you don't have conflicts later.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "templates, single" }
How to remove a large ugly space from my wordpress site? I'm sorry to ask such a simple question. You would think I would be able to figure it out on my own, but I've been up all night running in circles trying to remove a simple space from my website's homepage. Site is: ThePoint.news The space is between the header/social media links and "Trending Posts"... You can't miss it. My brain is fried from trying to get rid of this. I've looked at the code in the template, I've downloaded "space removing plugins", I've tried tweaking the theme.. everything. Yet I can not solve this simple problem. Any help would be so appreciated. Thanks... Image below of the hideous nuisance: ![enter image description here](
The space is coming from an empty div with ID "subfeatures". If you don't want this div you can remove it by changing the code or by using css div#subfeatures { display: none; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes" }
What order? register_taxonomy() register_taxonomy_for_object_type() register_post_type() In what order are these functions supposed to be called? register_taxonomy( $catname, $cpt ); register_taxonomy_for_object_type( $catname, $cpt); register_post_type( $cpt, $args );//without the taxonomies argument
Order really shouldn't really matter but it's good practice to register things in a hierarchical structure. register_post_type( $cpt, $args ); register_taxonomy( $catname, $cpt );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, custom taxonomy" }
Way to send multiple values for column to MySQL? I am creating a plugin that allows the user to select multiple options (as a checkbox), which sends these integer values to MySQL. The way I have this set up at the moment is by taking these values and passing them as a comma separate string. Then I take this string, remove the comma's, and pass the integer's as data. This intuitively doesn't seem like the most efficient way to accomplish what I am trying to do, so is there another method that can work better?
you can do it by using the array format. First you have to take all the selected values to form an array , you can implement this by giving the checkbox name as an array . By doing this you will get the array of selected check boxes in the name variable. You can also encode the array using Json_encode() before sending to database. <input type='checkbox' name='checkbox[]' value='One'>1<br>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, php, plugin development, mysql, phpmyadmin" }
Getting an error when trying to migrate to DV server from Grid with Media Temple Trying to migrate my wordpress site... getting this error: PHP Notice: Use of undefined constant DATABASE_SERVER - assumed 'DATABASE_SERVER' in /usr/share/plesk-wp-cli/php/WP_CLI/Runner.php(996) : eval()'d code on line 31 PHP Notice: Undefined index: DATABASE_SERVER in /usr/share/plesk-wp-cli/php/WP_CLI/Runner.php(996) : eval()'d code on line 31 {&quot;err_code&quot;:0,&quot;err_message&quot;:&quot;Error establishing a database connection&quot;} PHP Fatal error: Call to undefined function wp_cache_get() in /var/www/vhosts/gunprime.com/httpdocs/wp-includes/functions.php on line 1367 Fatal error: Call to undefined function wp_cache_get() in /var/www/vhosts/gunprime.com/httpdocs/wp-includes/functions.php on line 1367 Folowing directions from this site < I have uploaded the content and imported the old database. Can you help me get it working?
Had to update info in the wp-config.php file to match the new DB_NAME, DB_USER, DB_PASSWORD, DB_HOST
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "database, errors, installation, migration" }
Beyond widget side menu editing, with the php page, custom template Looking to reorder the side sub navigation to match the postings. How would I do this? Here is the page: < This is NOT controlled in the widget section, because it is a custom php page. The php page has them ordered by: 'orderby' => 'menu_order' Suggestions? Thank you. ![enter image description here](
What are the postings ordered by? If the postings query does not specify an `orderby` parameter then it would default to `'orderby' => 'date'`. In that case, just change the side menu's query to `'orderby' => 'date'` or remove that parameter from the query altogether. Here is a link to the available `orderby` options.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, menus, widgets, sub menu, menu order" }
sort query results by newest I wrote a query: WP_Query(array('post_type'=>'portfolio_item', 'post_status'=>'publish', 'posts_per_page'=>-5)); which works and does what I want except it sorts the results from oldest to newest, and I want them to appear newest to oldest. What can I add to the query parameters to make this happen?
WP_Query(array('post_type'=>'portfolio_item', 'post_status'=>'publish', 'posts_per_page'=>-5, 'order' => 'ASC')); See: < for order parameters. Hope that helps.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "query, sort" }
Migration of WooCommerce site I am new in WordPress. I am trying to migrate a WooCommerce site. What are the steps to Migrate a WooCommerce site? Where is the location of `.htaccess` file in a WooCommerce site? I migrated files and databases. I changed setting in `wp-config.php` file. I changed site URL in `wp-options` table of the database. But I found that my migrated site is not looking like the previous site, even I am getting `Not Found` error while I am trying to browse categories pages. Could anyone say where is the issue ?
It's not enough to edit `wp-config.php` file and `wp-options` table. You have to change **all** URLs and file paths in your database, including those serialized. Use WP Migrate DB or Duplicator plugins to do so. `.htaccess` file resides in the same server directory as `wp-config.php`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "migration" }
Why is my get_post_meta not properly calling the custom field when attempting to embed a YouTube video? I have added a custom field to 2 posts in order for a non-developer to be able to post a video link from YouTube, and put the embed id in a custom field to be called by the code below. But when I tried to execute it I get "An error occurred, please try again later." Upon inspection I find that it is trying to call the link as "< instead of filling in the youtubeId. <iframe width="100%" height="100%" src=" echo get_post_meta(93,'youtubeId');?>" frameborder="0" allowfullscreen></iframe> There is the code I am trying to run in a `<div>` in order to embed a YouTube link dynamically. Basically it is a lot easier for my non-developer content managers to edit a Wordpress post with an updated video than go changing the link in the actual page PHP/HTML.
By default `get_post_meta` returns an array. If you wish to return a single value you need to set the 3rd parameter to `true`. Eg. get_post_meta(93, 'youtubeId', true); And did you know that your client can just paste a youtube URL into the Wordpress editor and it will auto-embed that video? get_post_meta
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, embed, youtube" }
sql query not working in wp plugin I am trying to run the mysql query to count the record of last one month. Here is the query: $school_count_last_month = get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(),INTERVAL 2 MONTH)),INTERVAL 1 DAY) AND post_date <= DATE_SUB(NOW(),INTERVAL 1 MONTH)"); As this query working in phpmyadmin but when I tried to load my website not show anything. Although, I have tried another sql queries in same page, but they are working perfectly. Thanks
silly mistake, forgot `$wpdb`, it should be $school_count_last_month = $wpdb->get_var("SELECT COUNT(*) from $wpdb->posts where post_date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(),INTERVAL 2 MONTH)),INTERVAL 1 DAY) and post_date <= DATE_SUB(NOW(),INTERVAL 1 MONTH)");
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, mysql" }
A similar hook as wp_head for the admin area I'm adding a node to the toolbar and wish to tweak the css a bit. I don't have any external CSS files and I'm echoing the CSS using the `wp_head` action hook. Is there a similar action hook that I can use to echo the CSS everywhere? Both front-end and admin area?
The alternative to `wp_head` action in admin area is `admin_head`. But, if your CSS depends on another stylesheet, you should use `wp_add_inline_style()` function hooked to `admin_enqueue_scripts` action.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "admin, hooks, admin bar" }
Edit single page from plugin Hello guys I am creating a plugin in which I am making a custom post type season. Now I would like to echo something on season single page based on a database query. I have query and logics figured out but I want to echo on season single page from plugin file only not creating a single template and then use filter like post type template. If you could only show echo 'hello world'; on only post_type="season" that would be great. Thanks.
You could do this with the `the_content` filter: /** * Adds some text to bottom of the content on 'season' pages. * * @param string $content The current content of the season page. * @return string The new content of the season page. */ function add_season_content( $content ) { if ( is_singular( 'season' ) && is_main_query() ) { // collect your season data over here... $season_data = 'Hello world'; $content .= $season_data; } return $content; } add_filter( 'the_content', 'add_season_content' ); Place this code anywhere inside your plugin files.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, single" }
How to fix .htaccess corrupted I was working on the live site, I think the plugin cause file .htaccess corrupted so my site is down "500 Internal Server Error", I read a solution to rename .htaccess but when I use Filezilla to do it get "550 rename failed" so I can not rename it, I try to go setting -> save permalinks but not working. is there anyway other way to fix .htaccess error? please help me its emergency.
Try reverting back to the default `.htaccess` file with the following code: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress If you're using some other "flavor" of WP (e.g. multisite) view the htaccess docs on the Codex for the appropriate `.htaccess` setup.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "htaccess" }
How can I move the posted-on date above the post and below the entry-header? The posted-on date by default appears below the post. How can I move the posted-on date above the post and below the entry-header? I'm using a child theme of Twenty Sixteen. Because the post-on date is generated after the content, I don't believe a solution is possible with css.
To move the posted-on date above the post and below entry-header, copy the template-parts directory with only content.php and content-single.php from themes/twentysixteen/ into your child theme. In content.php, move `twentysixteen_entry_meta();` from the entry-footer div to just above the entry-content div. This will put the posted-on date above entry-content on all the posts. Do the same for content-single.php and that places the posted-on date above entry-content on single posts.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, hooks" }
Accessing WordPress using "localhost" and local ip at the same time I installed WAMP on Windows 10 and I can access my WordPress website using < However, when I try to access it from another computer using the local IP (for example < then that computer is redirected to < (because of **siteurl** and **home** options that point to < in **Settings -> General**, see Changing The Site URL) and thus I can't access the website from any network computer. The solution is to set **siteurl** and **home** to the IP < Then I can access the website from my computer and from all network computers. But the problem is as soon as I disconnect my computer from that network and lose my 192.168.0.70 IP I can't access WordPress at all (unless I manually update **siteurl** and **home** in the database back to "localhost"). Is there a way to be able to access WordPress in all three situations?
Set yourself up with a static IP address and then it won't ever change. See here for instructions on how to do just that. Any problems, post back. :) <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "urls" }
Exclude category from Tag Template I'm trying to exclude a category from my tag template. Searching gives me nothing and kinda stuck. When I add the code below to my tag template it shows all posts... and I really would like to show all posts with a specific tag, but not the ones from category ID 433. <?php $query = new WP_Query( array('cat' => -433, ) ); ?> <?php if ($query->have_posts()) : ?> <?php while ($query->have_posts()) : $query->the_post(); ?> So, this is not working :) Also tried this one: $query = new WP_Query( array( 'category__not_in' => array( 433 ) ) ); Also showing all posts. Hope anyone got an idea.
Have you tried using a normal loop in your tag template like this <?php while ( have_posts() ) : the_post() ?> //add content code or template <?php endwhile; ?> And then using the `pre_get_posts` filter like this function exclude_category( $query ) { if ( $query->is_tag() && $query->is_main_query() ) { $query->set( 'cat', '-433' ); } } add_action( 'pre_get_posts', 'exclude_category' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, templates, exclude" }
How to backup my site and restore my wordpress site My site, < is down hard. It looks like a problem with Wordpress. I want to back up my posts, etc. and then wipe everything and restore it to a fresh wordpress instance. Googling for backup and restore wordpress instance generated a zillion pages, but most are for backing up using a plugin or backing up all of the themes and everything else, which I wish to dump. Some docs say my posts are stored in MySQL databases, but where? I haven't found them. Also, I want to have a normal website for my root and move wordpress to a subdirectory when I pave and nuke the site. So how do I backup just my posts and restore them in the new wordpress instance?
you can use this SELECT * FROM databasename.wp_posts in mysql to view all your post; Then export it and then on the new database you can import the post.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, backup" }
Recommendations on accessing current user data in WordPress While reading the following WordPress Codex page on Global variable usage, there is a bold line that states ** > Accessing other globals besides the ones listed below is not recommended. ** My question is in concern to using the global variable `$current_user`. Is it not recommended to use something like this in my functions.php file? if ($current_user->display_name){ echo '<p>welcome ' . $current_user->display_name . '</p>'; } ...or are there other alternative methods I should start building habits on without depending on WordPress global variables not mentioned on that Codex page? I know what I am asking for probably doesn't have a black and white answer, but I would like to get the opinion from some of you guys how have been coding in wordpress for a while. Thanks
You can use `wp_get_current_user()` instead of using the `$current_user` global. $my_current_user = wp_get_current_user(); if ( $my_current_user->display_name ) { echo '<p>Welcome ' . $my_current_user->display_name . '</p>'; } Note that I used `$my_current_user` instead of `$current_user` as a variable name, because you can run into trouble if you use the global variable's name.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "globals" }
Adding anchors in Wordpress Menus I am looking to add the option of adding an anchor to my page in the Menu's page. By default, the link has the `Navigation Label` with the link to the page, a `Remove` and a `Cancel` link. However, I need to add a page with a named anchor. So far, I've added all my links with `Custom Links`, but I would prefer being able to add my page in case my `slug` changes. Is this possible via `functions.php`, or perhaps a plugin?
There's a specific filter for each nav item's attributes: nav_menu_link_attributes. So, you can put in your functions.php file something like: function mysite_add_anchor( $atts, $item, $args ) { $atts['href'] .= ( !empty( $item->xfn ) ? '#' . $item->xfn : '' ); return $atts; } add_filter( 'nav_menu_link_attributes', 'mysite_add_anchor', 10, 3 ); What this does, is check the Link Relationship (XFN), and if it's not empty, it will add that to the end of your link with the #. A couple things, if you don't see "Link Relationship" in the menu item, check the "Screen Options" at the top and check the box. ALSO, you can use almost any of the other properties you aren't currently using for Advanced Menu Properties. < Not sure if Link Relationship isn't the right one, but it's the one I use the least. Note: I didn't test the code.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "menus" }
WP-RestAPI and xml sitemap Using the WP-RestAPI to pull a wordpress blog into an angularjs application. Works extremely well. The blog is using Yoast SEO for the for meta descriptions and keywords. I would like to use the yoast xml sitemap as well for submitting to google. However, because of route structure I need to save the sitemap to a different location than the root wordpress folder. I have also tried using the Google Sitemap Generator plugin. With neither plugin can I seem to change where the sitemap is saved. Looking for any advice on how I could make this work.
Let's assume your plugin is writing to the `/usr/share/wordpress/sitemap_index.xml` filesystem location, but you want it can be accessed through ` as if the xml file were stored in `/var/www/html/sitemap_index.xml`. You can use the alias directive then, available in mainstream webservers Apache and NginX: For an alias in NginX, you put this inside the `server` of your public website: location /sitemap_index.xml { alias /usr/share/wordpress/sitemap_index.xml; } For Apache the alias it's like this, inside the virtual host of your website: Alias "/sitemap_index.xml" "/usr/share/wordpress/sitemap_index.xml" Again, I'm only assuming filepaths and filenames, but if you need more specific directives, for another webserver, or differente paths/names, please comment it, or even better: update your question to make my answer match.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin wp seo yoast, rest api, google xml sitemaps" }
Use another author.php if different multisite subsite? I have a multisite installation with 2 subsites (site A, site B) using same theme. Is it possible to use a different author.php if Im on the site B? Assuming the second author template exists. For exeample.. if (blog_id == 2){ // use this template diff-author-template.php } else { //use this author.php} Thanks
This was the solution.. // different author template */ add_filter( 'template_include', 'author_template', 99 ); function author_template( $template ) { if( !is_main_site() and is_author( ) ) { $new_template = locate_template( array( 'other-author.php' ) ); if ( '' != $new_template ) { return $new_template ; } } return $template; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite, templates, author" }
How to get the Custom Post Type Archive inside a folder I have archive-teachers.php which is not yet inside any folder and it was working fine. But when I transfer the archive-teachers.php in the archive folder, it stop working everytime I check the url /teachers/. So I put back the archive-teachers.php back together with the header.php. Then I created a parent of the teachers which have the url school/teachers/ but now the archive-teachers.php is not working anymore. Before, I just create a blank page named Teachers and it was able to call the archive-teachers but when I create a parent page of teachers, it stopped working. I would like to ask help with you guys on how can I solve my problem. First, will be able to use the archive-teachers.php inside a folder and second, how can I call or access the archive-teachers.php inside the folder in the url of /school/teachers/ Please give some advise.
That a normal behaviour of WordPress. Have a look to te template hierarchy template hierarchy. To solve your matter, leave your file in the main folder of your theme (or child theme) or use a template_redirect or template_include filter, depending how you want to call your archive page, you'll be able to redirect to another template file or include the file you want. For instance, archive folder is not a folder that WordPress will detect when it want to load a template, you need to tell to WordPress, where is the file you want to load for your special query.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "archives, custom post type archives, archive template" }
Plugin stable tag on wordpress.org not updating What am I doing wrong? It should be at version 1.4 now, but is still at 1.1. <
The read-me.txt show a stable tag to 1.3 that you must edit in the trunk folder to be 1.4. At this time, the read-me tell I'm with a stable tag of 1.3 so go in the folder tags/1.3, and the wk-ga.php show a value of version 1.1. You need to change the version number in wk-ga.php in your tags directory, according to the trunk (and tag too) read-me file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins" }
Theme or Plugin: Where should I write my code? I'm facing a dilemma - whether to add my code into a theme or plugin? I'm creating an events plugin (/theme) that would allow college students to post their events and once approved, these events would be displayed to all. While 'Create an event' form can be rendered using shortcode, I'm concerned about putting up event search pages, list of events (there will be thousands of events), 'My Events', 'Favorite Events' etc. Should these be rendered using shortcode OR as theme pages? Would really appreciate your suggestions. Thank you for your time.
How Sharma just mentioned, both approaches are working well, but depending on the site type and scope and also it depends on the feature that needs to be implemented in your WordPress. If in the future you will change the theme of your WordPress site and you just implemented a feature in your current theme, it will be lost. How the sketch below shows, I suggest to add your design in theme or child theme (recommended) and all functionalities in a plugin ![enter image description here]( I always add shortcodes, widgets, custom post types and metaboxes in plugin because the theme will not be same forever but this way the functionalities from the plugin will be kept. Hope this answer your question;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, themes" }
Missing wp-load.php on new install I am technically proficient, but am new to administering a wordpress site. I have a basic wordpress site for which I simply do some blogging, no plugins. I have exported the data using the myphpadmin in cpanel. I nuked the site and create a new one through the installer. I then reloaded all of the data through the SQL interface. Now when I navigate to www.forerunnerintl.org/blog I get: Warning: require_once(/home/forerunn/public_html/blog/wp-load.php): failed to open stream: No such file or directory in /home/forerunn/public_html/blog/wp-blog-header.php on line 13 Fatal error: require_once(): Failed opening required '/home/forerunn/public_html/blog/wp-load.php' (include_path='.:/opt/php54/lib/php') in /home/forerunn/public_html/blog/wp-blog-header.php on line 13 I looked and that file is not there, but I have no idea how to create it.
As socki03 suggested, I downloaded and upload a fresh install and things are now limping along a bit. I'm posting the configuration issue I'm having in another question. Thanks for the help.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "installation" }
Check if we're viewing an event I need to know how to check if the user is looking at an event or the list of events from the plugin The Events Calendar on my custom theme's page.php. One solution I thought of was to grab the url. mysite.com/events shows the list of events, and mysite.com/event/theevent shows a specific event. I thought about grabbing the permalink using `get_the_permalink()` / `get_permalink()` and checking if it contains event/events, but that doesn't seem to be returning anything for me while on an events page. Or if I could set the category (the actual wordpress category, not the calendar category) to something like "events" I could use has_category('events'), but I don't know how to do that.. Any suggestions? * * * Edit: I went snooping around in The Event Calendar's php files and found `tribe_is_event()` and I'm able to determine if the page is an event, but only **after** `the_content()` has been called. I need to know _before_ that happens.
You can get the post id outside the loop with `$wp_query` and then feed it to `tribe_is_event()`. works a treat. <?php global $wp_query; if (tribe_is_event($wp_query->post->ID)) {echo "yup"; } else {echo "nah"; } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, theme development, the events calendar" }
Ninja Forms: "Unknown Field type "" not found." I cannot figure out why Ninja Forms is throwing this error. Documentation does not have anything available on this error. If I am making a form, and the field key is _firstname_ , this error will come up and say it's not found when I go to publish it, and it corrupts my form. > Unknown Field type "" not found. Any advice would be great. Thank you!
Please use Ninja Forms support. They recently made a large update and are continuously making improvements.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin ninja forms" }
Wordpress not handling subdirectory properly I have placed a new wordpress install in < and it seems to be running and have my old posts that I updated. All the links, though, go to < instead of < and so they are all dead. How do I configure wordpress to handle the subdirectory properly? I'm having problems logging in as well since those links are also dead.
Read < and updated two fields in the wp_options table: siteurl and home. After updating both of these, my site appears to be working correctly.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "directory, installation" }
Error 404 Page Not Found When Updating a Post or Page Help! All of a sudden my Wordpress admin has started showing a 'Error 404 Page Not Found' message whenever I try to update an existing post or page on my site. Creating new posts and pages works fine. This happened suddenly last night when I was updating a series of posts and it suddenly started showing this message. So far I have tried: 1. Settings > Permalinks Save button 2. Disabling all plugins 3. Updating all plugins 4. Changing theme 5. Deleting all WP content apart from wp-config.php and wp-content folder, and uploading fresh Wordpress install 6. Updating Wordpress I'm not sure what else to try?
Updating Permalink changes update your permalinks settings and flush rewrite rules. In most cases this fixes the WordPress posts 404 error. BTW, you already tried this and I hpe your `.htaccess` should be writable. Have you checked it? If not then you can change `.htaccess` file permission temporary writable by changing the permissions to **666** and make sure after after 'Save Changes' action turn back `.htaccess` permission.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 5, "tags": "errors, 404 error" }
WordPress not showing recent posts For some reason, when a new post is published, it doesn't show up in its category page unless I am logged in. I built a custom theme, and have in no way specified anything that should cause this to happen. It's especially strange because they do show up when I'm logged in. And, no, the posts aren't private. This is how I've defined my loop: <div class="content-categories-wrapper"> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); get_template_part('content', get_post_format()); endwhile; ?> </div>
It sounds like there may be a caching plugin installed. If so, clear the cache.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories" }
How to show another link post from another blog multisite? Is there any code or plugin to insert another link post from another blog multisite?
Best and simple method to Insert / display articles from another site or multisite is to use wordpress inbuilt RSS Widget. Or else you can try the following plugin < < Hope this helps!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite" }
Woocommerce view order link in customer emails I am trying to figure out how to add a clickable link in the e-mails to my customers that takes them directly to the view-order page (myurl/my-account/view-order/xxx/). I have found some code that comes close, but the link doesn't work when I add it to the email templates. printf( __( 'Order: %s', 'woocommerce'), '<a href="$order->get_view_order_url()">'. $order->get_order_number() .'</a>' ); I know of a paid plugin that does it, but I am trying to cut down on the use of plugins, especially for something this simple. This is the plugin: <
Try changing that code to this: printf( __( 'Order: %s', 'woocommerce'), '<a href="' . $order->get_view_order_url() . '">'. $order->get_order_number() .'</a>' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "woocommerce offtopic" }
woocommerce - hide payment method in new order email I am using woocommerce 2.6.4 and I am trying to customize the email customer gets as confirmation for new order. I need to hide Subtotal and Payment method from the order details within the email template. I manged to hide subtotal with the following code I put in functions.php: add_filter( 'woocommerce_get_order_item_totals', 'adjust_woocommerce_get_order_item_totals' ); function adjust_woocommerce_get_order_item_totals( $totals ) { unset($totals['cart_subtotal'] ); return $totals; } ?> Is there any way to hide the payment method as well? Thank you all in advance.
I manged to figure this one out. For anyone having the same problem maybe, here is the solution. Just add unset( $totals['payment_method'] ); before return $totals;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, woocommerce offtopic" }
$wpdb->base_prefix not get parent site prefix in multisite I am using three site multi-site installation. When I use `$wpdb->base_prefix` some time it gives network site prefix instead of giving base site prefix. Any one face this problem? Can you please give any suggestion?
`$wpdb->base_prefix` gets the original prefix (ie, the 'root' site in a Multisite installation). It was added in Version 3.0.0, right when Multisite became a part of WordPress core. `$wpdb->prefix` will get the prefix for the current site in a Multisite installation. Per the documentation for the `wpdb` class: > **$prefix** > The assigned WordPress table prefix for the site. > > **$base_prefix** > The original prefix as defined in `wp-config.php`. _For multi-site: Use if you want to get the prefix without the blog number appended._ (emphasis added)
stackexchange-wordpress
{ "answer_score": 15, "question_score": 8, "tags": "multisite" }
Why is flush_rewrite_rules mandatory after registering custom taxonomies? I'm a newbie in the world of WP plugins. I succesfully created custom post types and taxonomies and all is working well. I have no idea of why we need to invoke `flush_rewrite_rules()` after registering custom taxonomies. It's a loose of time, for me, because it will recreate `.htaccess` from scratch. But why? Why to recreate the `.htaccess` file ?
It's an expensive operation, so rather than it happening automatically you have to run it somewhere when you know your rewrites have changed. There are also circumstances where WP may not know it needs to flush the rules: Deletion of a plugin that registers a CPT for example. In your own plugin, run it on the activation and deactivation hooks. If you use `flush_rewrite_rules( false )` then your `.htaccess` won't be resaved.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, htaccess, rewrite rules" }
Wordpress function and string as variable? I am creating something which passes featured image URLs to a separate JavaScript file which uses `parallax.js` to create a parallax background for each entry for an archive page. This works fine when each post has an image. I have been working on having a default image where there is no featured image but am having problems on pointing to it. I want to keep the path relative so when I upload to the host there is no need to have an absolute path. At the moment it goes something like this: if ( has_featured_image() ) { $image_link_url = $featured_background_image; } else { $image_link_url = get_template_url() . 'images/placeholder_bg.png'; } This does not work. How would I get the result I am after? Ideally want to have the function result and string at the end as one single string in a variable.
Instead of `get_template_url()` user `get_template_directory_uri()` for parent theme and `get_stylesheet_directory_uri()` for child theme or parent theme if not child theme present NOTE: this will require a slash like so: $image_link_url = get_template_directory_uri() . '/images/placeholder_bg.png';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, post thumbnails, variables, query string" }
Wordpress Active Plugins I have in my website right now around 100 active plugins. I need to know a way to erase those active plugins that I'm not using. Actually that is affecting the speed of my website and back-end too. In my side I found that does not exist a plugin that can tell me this... Any suggestion, any advice will be really appreciate it.
I'd recommend < to see what plugins are slowing you down. The only way to know which plugins you are not using would be to check if/where they are used and for what. You COULD deactivate one by one and make sure nothing breaks on the site. There is otherwise no other way of knowing which you are or are not using.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
Clean way of using ob_start() and ob_end_clean() in wordpress I want to pass some json data to JS from wordpress(PHP) and was thinking to use `ob_start()` and `ob_end_clean()` in wordpress but i am not sure weather any other plugins are using the same functions. I was thinking to manually add `ob_start()` at the beginning of the theme header and clear the document when necessary. I thought of using grep find if there are any `ob_start()` in wordpress, but i can't grep find everytime my website gets updated. Are there any workarounds? I will be calling `ob_end_clean()` from a shortcode.
WordPress has a whole set of useful functions to handle. It's called wp_send_json(). You have success and error functions too. `ob_start()`, `ob_get_clean()` would be useful in case you want to include some views (~ MVC) in your shortcode, e.g in your shortcode handler. I don't see here why you would use them to pass data from PHP to js. Otherwise I would use them in the shortcode handler, no use to put them in theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, function exists" }
How do I reformat this to add php inside php? I currently use this conditional code... <?php if ( $paged < 2 ) echo 'some text'; else echo 'some other text'; ?> I need to add some more php between the 'if' and 'else'... <p>Text...<?php $published_posts = wp_count_posts('item'); echo $published_posts->publish; ?> text... <?php echo do_shortcode("[count]"); ?> text.</p> ...so that it'll be something like this... <?php if ( $paged < 2 ) echo 'some text'; <p>Text...<?php $published_posts = wp_count_posts('item'); echo $published_posts->publish; ?> text... <?php echo do_shortcode("[count]"); ?> text.</p> else echo 'some other text'; ?> That obviously won't work, but I don't know enough to recode it.
> As PHP documentation says > > Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. So You have to use `curly braces` `{}` to add more statement within `if` `else` <?php if ( $paged < 2 ) { echo 'some text'; ?> <p> Text... <?php $published_posts = wp_count_posts('item'); echo $published_posts->publish; ?> text... <?php echo do_shortcode("[count]"); ?> text. </p> <?php } else { echo 'some other text'; } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "php, conditional content" }
White screen after plugins upgrade For some reason when I upgraded all the plugins, I got a white screen. Is there any way to debug it?
Connect to FTP using FileZilla. Rename each plugin folder name one by one and see which plugin is causing the issue. Once you found out the plugin which is causing the problem. Just reinstall it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Wordpress "remember me" - How should it work? In my installation WP 4.6.1, on login forms the checkbox "Remember me" may be used, however credentials will be empty on next login. Users usually logout, I wonder if this is the problem, or should the browser (cookie) remember credentials? In a few words: how the "remember me" option should work?
This checkbox is under the supervision of the browser cookies. Users can disable the `Save password` function globally or on the per-site basis. Also, sometimes browsers ignore this checkbox due to some reasons, especially with some cookie-related add-ons installed. For example, my clean installation of the latest Chrome on Ubuntu 14.04 started to decline to save passwords one day, whereas it still offers me to save them.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp login form" }
Correct meta of Writing Meta Tags How to write this Head section thing correctly in Wordpress. <meta name="author" content="The Zebra Team"> <meta name="description" content="The Zebra Team"> I was doing it like this - <meta name="author" content="<?php the_author(); ?>" > <meta name="description" content="<?php the_content(); ?>" > But then it was not showing me anything in the head section. I think I am doing it correctly then what is the issue?
I think you have to check if the loaded page is a post, and use the Wordpress loop to get the right data. <?php if ( have_posts() ) { while ( have_posts() ) { the_post(); ?> <meta name="author" content="<?php the_author(); ?>" > <meta name="description" content="<?php the_content(); ?>" > <?php } } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, headers" }
How to apply editor filter to posts with a specific custom post type How can we apply filters only to posts with a specific custom post type? I would like some of my custom posts to start out in HTML mode for their editors. This is what I am working with so far... add_filter( 'wp_default_editor', create_function('', 'return "html";') );
You can determine the current post type using `get_post_type()` inside the callback function hooked to `wp_default_editor`: add_filter( 'wp_default_editor', 'wpse242896_wp_default_editor' ); function wpse242896_wp_default_editor( $editor ) { $post_type = get_post_type(); if ( 'custom_post_type' === $post_type ) { return 'html'; } else if ( 'other_post_type' === $post_type ) { return 'tinymce'; } return $editor; } Also, anonymous functions are generally discouraged because they can't be unhooked very easily.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "editor" }
Wordpress Theme Conflict With Plugin I have updated the Wordpress to the Latest Version of it as well as the Plugins of my site. and I notice that the I can't transact any order in my site. I seems that the whole functionof Woocommerce is not working properly. can the downgrading of the Woocommerce will fix the issue? What can else can I do except with the Upgrading of the theme it self.
I found the solution on the problem with Downgrading the Woocommerce based on the Theme Woocommerce. The steps would be: 1. Deactivate the Current Woocommerce Plugin 2. Using FTP or File Manager delete the content of the folder "woocommerce" 3. Download the Older Version of Woocommerce 4. Unzip and Upload using FTP 5. Activate again the Plugin
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, woocommerce offtopic" }
Keep js after reload the page I have some links and calls the click function in js when click on specific link. like below jQuery(document).ready(function() { jQuery("a.music").on( 'click', function () { var tags = jQuery(this).attr("data-tag"); document.cookie = "tags=" + tags; console.log(document.cookie); location.reload(); jQuery(this).find('h4').addClass("a-active"); jQuery(this).find('h4').css("color","red"); }); }); The thing is I have to set cookie and get this cookie on that current page so I have to reload the page to get the update cookie everthing times click another link. but after the page reloaded, all the css or adding new class that I did by jquery all dissapear. Like it just happens for a while untils the page reload. Please give me ideal if you know what I did wrong here. Thank you
I understand, that you want "a.music" remain set active after you reload the page. For that you can check whether the cookie is set or not if it is set you make active to the "a.music" else it will remain as same. var tags = getCookie('tags'); jQuery('a.music').each(function(){ var dTag = jQuery(this).attr("data-tag"); if(dTag == tags) { jQuery(this).find('h4').addClass("a-active"); jQuery(this).find('h4').css("color","red"); } });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions" }
How to make a search button that will search my website? I want to make a search button that search only within my website. 1. Do I need external PHP or PERL script? 2. Can it done by JavaScript? 3. Or simply by HTML. I tried to create a form using HTML: <form> <input type="search" name="banner_search" class="banner-text-box" > <input type="submit" name="" value="SEARCH" class="banner-text-btn"> </form>
You can use WordPress's internal search by calling the `get_search_form()` function: <?php get_search_form(); ?> `get_search_form()` will use a default HTML form, but you can create your own custom form by adding a `searchform.php` file to your theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, search, buttons" }
Do we have rights to edit the source of the templates which are in wordpress.org? I want know about is, can we edit the source code of themes which can be download in wordpress.org Do we have rights to edit the source code and, add our own copyright to footer?
Normally you can find information regarding the license in the `style.css` file located in the root of the theme. Open it with a text editor (or in the admin panel `Administration > Appearance > Editor`) and check the comment, if it says something like this: > License: GNU General Public License v3 > > License URI: < Then you are free to modify it however you like. If there's no information regarding the license in this file, then check the folder for README file, but in most cases it should be in `style.css`. I believe that most if not all official Wordpress themes are under GNU license, but it's always better to check your theme before editing it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "themes, copyright" }
Multiple Meta_values As you an see I use a `get_pages()` function and it all works fine. $city_ids = get_pages(array("hierarchical" => 0, "sort_column" => "menu_order", "sort_order" => "desc", "meta_key" => "page_type", "meta_value" => 1)); But now I want multiple meta_values. I tried things like: "meta_value" => 1,3 "meta_value" => 1 AND 3 But they both don't work. Is there any way to do this? Thanks in advance.
$args = array( "numberposts" => -1, 'post_type' => 'page', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'page_type', 'value' => 1, 'compare' => '=' ), array( 'key' => 'page_type', 'value' => 3, 'compare' => '=' ) ) ); $city_ids = get_posts($args);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "meta value" }
Can't upload the theme When I upload a theme on wordpress I get this message ![enter image description here]( Since I'm new to WordPress, What I have to do?
It seems that you had upload that theme earlier. Go to Media, then find the item which has the same name of the theme you want to upload. Click it, and delete it. After that upload your theme again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "themes, uploads" }
CountPost WordPress Custom Taxonomy What's the easiest way to add "count posts" to the category listing as seen as below? <?php if($categories){ foreach($categories as $category) { $output .= '<li><a href="'.get_category_link( $category->term_id ) . '" title="' . esc_attr( sprintf( esc_html__( 'View all posts in %s','themename' ), $category->name ) ) . '">' . $category->name . '</a></li>' . $separator; } echo trim($output, $separator); }
I do not know exactly what you mean, but I think you need something like this? $categories = get_terms( array( 'taxonomy' => 'category' ) ); if ( $categories ) { $output = ''; foreach( $categories as $category ) { $output .= '<li title="' . __( 'View all', 'themename' ) . ' ' . $category->count . ' ' . __( 'posts in', 'themename' ) . ' ' . $category->name . '">' . $category->name . ' ' . $separator . '</li>'; } echo trim( $output, $separator ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "count, listing" }
How to create a table with filters for my plugin I'm developing a WordPress plugin and I need to create a page for products/plans and I need to create that page with a table, filters and a top button "Add New", how can I do that? This page for products/plans should be a custom post type?
There are two standard way of creating admin listing table in wordpress. 1. Using **register_post_type** 2. Extend **WP_List_Table** class by copying it in our plugin because it's a core class that can be modified by WordPress, It's located inside (/wp-admin/includes/class-wp-list-table.php) directory.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development" }
Single central login for front end users from any site I have multiple websites with one master site. Is it possible that used register and login using a single username and password on all the sites. the installations are not wordpress multisite,each site is a individual website.
this is very possible. I've done this in the past if they are in the same table but with the different extensions: (if they aren't then you can merge the 2 tables) blog 1 (table prefix is ba1_) blog 2 (table prefix is bb2_) so you you would have 2 user tables in your database: ba1_users bb2_users In your wp-config of the 2nd blog: find this line: /* That's all, stop editing! Happy blogging. */ Just above it, add: define('CUSTOM_USER_TABLE', 'ba1_users'); define('CUSTOM_USER_META_TABLE', 'ba1_usermeta'); now blog 2 which was using bb2_users and bb2_usermeta will now use ba1_users and ba1_usermeta. I haven't fully explored all considerations but this worked really well for me.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, login" }
How do I correct this filecount? Although this is more of a generic php question than specifically WordPress, it relates to a function used in WP and so I've posted here. I use the code below to provide a count for the number of article authors (there's one jpg per author in a folder). The published count is one more than actual... currently, for 53 jpgs it shows 54. function item_count() { $dir = 'PATH TO FOLDER'; $filecount = 0; $d = dir( $dir ); while ( $f = $d->read() ) { if ( ( $f!= "." ) && ( $f!= ".." ) ) { if( ! is_dir( $f ) ) { $filecount++; }}} return '' . $filecount . ''; } add_shortcode( 'count', 'item_count' );
You're right - this is very much a generic PHP question. But fwiw, the issue is that you clearly want to count all _JPEG_ files, but your sample code counts _all_ files - so... while ( false !== $f = $d->read() ) { if ( in_array( strtolower( pathinfo( $f, PATHINFO_EXTENSION ) ), [ 'jpg', 'jpeg' ] ) ) $filecount++; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
How to check category of of custom post type or not I have a `category.php` file in my theme. Now the problem is in wordpress category can be of many things. Like there is a default blog post category. Then there are category for custom post types, like portfolio, logo etc. Now for all of these categories the same `category.php` file gets fired. But in my `category.php` I'm trying to show something only if it is the category of main blog post type. If it is the category of any other custom post types, then that thing will now show up. Is there is way to check if the category is of default blog post type or some custom post types? So that I can do something like this: if( this is the category of the main blog post type ) { // then show what I want } else { // don't } Thanks in advance.
So basically you want to use the `category.php` for a particular `post_type`'s category, right ? I think you can make sure the thing like below- if( 'your-main-blog-post-type' == get_post_type() ) { // then show what I want } else { // don't } Use above logic in your `category.php` and I hope you'll get the solution you're looking for.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, theme development, themes" }
What does apply_filters() do exactly? I'm new to WordPress development and was just thinking of adding some functionality to a widget. I have been seeing some people using this: $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base ); And some people this: $title = ( $instance['title'] ) ? $instance['title'] : ''; In my case I want to add a link to a button but I am not sure if I should use apply filters on it or not. $buttonLink = ( $intance['buttonlink'] ) ? $intance['buttonlink'] : '';
The `$instance['title']` corresponds to the title enter in the widget. When a plugin or a widget as an apply_filters, the developper gently had a way to override the current value sets for the title. Now, imagine you setted a title (in the widget setting panel) but you want to change this value only if user is logged in. You just have to add a filter in your functions.php add_filter('widget_title', 'logged_title'); function logged_title($title){ if(is_user_logged_in()){ // don't forget to test your widget id $title = 'new widget title'; } return $title; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "widgets" }
Convert each new line in the textfield as a new value in an array In my plugin, I've created a textfield (ID: `main_menu`) that allows the users to list the admin menu items by their menu slug (ex: `index.php` = _Dashboard_ , `plugins.php` = _Plugins_ , etc.): ![]( It's important that the user enters each menu item in a new line so this can convert it to an array. Right now, when the user enters in their input on each line, the value for that textfield is treated as one item when I `echo` the `get_option()` for that field. How do I convert each new line input that's entered into an array loop of multiple values?
To do so, you will want to use the `explode()` function to break up each new line (`\n`) into another array value. Also it is important to replace the invisible Carriage Return which is also used as a new line character by Mac OS: # Get the plugin options $settings = get_option( 'myplugin_menu' ); if ( isset( $settings['main_menu'] ) ) { # Convert each new line in the textarea as an array item $menu_slug = explode( "\n", str_replace( "\r", "", $settings['main_menu'] ) ); foreach ( $menu_slug as $key => $value ) { # Remove each menu item remove_menu_page( $value ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, array, admin menu" }
remove_menu_page doesn't work on custom plugin menus Using the `remove_menu_page()` function works for removing the default admin menu items by their slug like so: add_action( 'admin_menu', 'hide_menu' ); function hide_menu() { remove_menu_page( 'index.php' ); // Dashboard remove_menu_page( 'tools.php' ); // Tools } When a plugin created their own menu in the Dashboard, the URL structure looks like the following: However when trying to remove the custom plugin menu item like so: remove_menu_page( 'admin.php?page=plugin-slug' ); Nothing changes. Looking at a similar questions here and here, it seems that my function isn't called in time once the custom plugin settings load? Yet, when I try to increase the priority to a higher number, that still doesn't work: add_action( 'admin_menu', 'hide_menu', 9001, 1 ); Is there a work around? Am I doing this correctly?
Thanks to the answer that the_dramatist posted, it was a matter of just hooking to the `admin_init` tag. The slugs for those plugin pages can be retrieved by the debug script that the_dramatist provided, or you can simply look at that query value after `admin.php?page=plugin-slug`: add_action( 'admin_menu', 'wpse_243070_hide_menu' ); function wpse_243070_hide_menu() { remove_menu_page( 'index.php' ); // Dashboard remove_menu_page( 'tools.php' ); // Tools remove_menu_page( 'plugin-slug' ); // Some plugin remove_menu_page( 'another_slug' ); // Another plugin }
stackexchange-wordpress
{ "answer_score": 8, "question_score": 6, "tags": "admin menu" }
hide/show a div in wordpress How can I make my `<div id='banner'>` visible only in index.php and hide it on other pages like single.php in WordPress? My `div id='banner'` is located in my header and the header is displayed on all pages with `get_header();`
Detecting _index.php_ specifically may not be the best option because this template file is used in many cases in WordPress. Eventually, all pages will fall back to using index.php if no other template file is associated with this page. So instead of targeting _index.php_ , get familiar with template hierarchy and try to use conditional tags, whenever possible. For example, if you want to display the banner only on archive pages you could do something like: <?php if ( is_archive() ) : ?> <div id="banner"> <!-- Banner content goes here. --> </div> <?php endif; ?> Similarly, you can combine conditional tags: <?php if ( is_front_page() && is_home() ) : ?> <div id="banner"> <!-- Banner content goes here. --> </div> <?php endif; ?> This way your code will be future-proof and compliant with WordPress Coding Standards.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, conditional content, design" }
"Deregister" plugin from frontend or specific pages? Is is possible to stop plugin from loading on general frontend or on specific pages, similar like we can do with deregistering scripts and styles? Plugins are not mine and I only need them in the admin dashboard. Inspecting website with Query Monitor I noticed that they do additional useless queries like this SELECT option_value FROM nk_options WHERE option_name = 'wp-smush-resize' LIMIT 1 SELECT option_value FROM nk_options WHERE option_name = 'wp-smush-resize_sizes' LIMIT 1 I can't see the point of this. In this example plugin is WP Smush which only optimizes images when they are uploaded in backend. But there are a few more like WP/LR Sync and others, and they are not related to frontend... Is there something I could do on my theme files or inside Wordpress to stop them from doing additional database queries?
Replace the `/your-page-slug/` with your desired page where you want to disable the plugin and `plugin-folder/plugin-main-file.php` is plugin directory and plugin main file name with `.php` extension. add_filter( 'option_active_plugins', 'the_dramatist_disable_plugin_on_certain_page' ); function the_dramatist_disable_plugin_on_certain_page($plugins){ if(strpos($_SERVER['REQUEST_URI'], '/your-page-slug/') === FALSE && strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE) { $key = array_search( 'plugin-folder/plugin-main-file.php' , $plugins ); if ( false !== $key ) unset( $plugins[$key] ); } return $plugins; } Hope this piece of code help you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Get WP All Export row ID Is there a way to get current row's ID/number while exporting orders with WP All Export plugin (< First row would contains the columns' name, but we need that the first column contains a growing number, so second row (which contains first order details) first column value should be 1; third row (which contains second order details) first column value should be 2; etc... Situation is complicated because orders export limit is 50 (In each iteration, process 50 records), so if you have 60 orders 51. order's first column should be 51, not 1. I have tried with $i variable and $_SESSION[] variable too, but this are not the best solutions.
We've got a solution from plugin's developers: 1. Add this code to theme's functions.php file `// run a function before export starts, it deletes counter value from DB add_action('pmxe_before_export', 'wp_all_export_pmxe_before_export', 10, 1); function wp_all_export_pmxe_before_export($export_id) { delete_option('wp_all_export_current_row'); }` 2. Add this to All Export plugin's Edit Export screen under " Export the value returned by a PHP function" section `// update counter value while exporting function get_row_number() { $current = get_option('wp_all_export_current_row', 1); update_option('wp_all_export_current_row', $current + 1); return $current; }`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, export" }
Problem moving my WordPress live site to localhost I downloaded all the contents of my WordPress site (from `httpdocs`) into a folder `C:\xampp\htdocs\test-site`. My XAMPP/Apache runs at `port 8080`. I also downloaded a `dump.sql` file of the database and changed the path from `www.mysite.com` to `localhost:8080/test-site`. Created the new database in my `phpmyadmin` and uploaded the modified `dump.sql`. I also modified the `wp-config.php` for the database name, the usernamne (`root`) and the password I use locally. When I give the site url in the browser (`localhost:8080/test-site`) it returns automatically to `localhost:8080/dashboard` (Welcome to XAMPP screen). Do you have any idea how to fix this and manage to make my site work locally? **Update** In the `access.log` of Apache I get the following message: `"GET /test-site/ HTTP/1.1" 302 - "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"`. It might helps.
Finally it was solved as follows: 1. Enabled debug option in `wp-config.php` 2. After several tests I found that a plugin (polylang) causes a conflict with Cherry Framework which I use with my template. I Removed the polylang plugin directory and managed to login WP admin. Since I use Cherry Framework I got an error message (File Not found) for `wp-content/themes/mytheme/bootstrap/less/bootstrap.less` and `wp-content/themes/mytheme/style.less`. So I removed the `bootstrap.less.cache` and `style.less.cache` from the corresponding folders. 3. After I logged in the WP-admin reinstalled the plugin and everything came back to normal.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "localhost" }
If its not frontpage Could somebody please tell me how to write <?php if (in_category( array(10,11,12,13,14,15,18,19,20) )) { ?> and if its not frontpage ?
You have the WordPress function is_front_page() that you need to invert with "!" . if(!is_front_page() && in_category( array(10,11,12,13,14,15,18,19,20) ))
stackexchange-wordpress
{ "answer_score": 9, "question_score": 3, "tags": "homepage" }
If there is only one post (show elements) else (show other elements) So I'm looking for some help on an if statement: <?php if(i dont know what to put here. [something like is-single-post]){ ?> <div class="one post"></div> <?php }else{ ?> <div class="multi posts"></div> <?php } ?> Also this is a **custom post type** with a slug of **post** [ don't ask ( ͡° ͜ʖ ͡°) ]. So im sure that will make a difference. Is there a way to do this?
You can get the number of posts in the current loop from the `$wp_query` object. How you do it will depend on whether you use the main loop or a custom one. ### Main loop Use the global query object. <?php global $wp_query; $is_single_post = ($wp_query->post_count === 1); ?> <?php if ($is_single_post): ?> <div class="one-post"></div> <?php else: ?> <div class="multi-post"></div> <?php endif; ?> ### Custom loop Use your own query object. <?php $args = array( // fetch post type and whatnot ); $query = new WP_Query($args); ?> <?php if ($query->have_posts()): ?> <?php if ($query->post_count === 1): ?> <div class="one-post"></div> <?php else: ?> <div class="multi-post"></div> <?php endif; ?> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, posts" }
What is most efficient way to migrate wordpress website? There are following ways to migrate a WP website: 1\. Via FTP, download all files under public_html and export full database to local computer, and then upload the two to client's shared hosting server. 2\. Migrate via plugin, but it doesn't always work, or I may not be using the right plugin. 3\. Install another fresh installation (from wordpress.org) of Wordpress at client's shared hosting and move the exported database and wp-content folder to client's server. I want to know the quickest, most efficient and userfriendly way, that saves bandwidth (means less size of movable data), to migrate the wordpress website to client's folder. Also if somebody can suggest me the best plugin to do so. I'd prefer to do it by moving database and wp-content folder only, is it the right way to migrate Wordpress website?
I use All-in-one WP Migration. It handles the database search/replace automatically, and lets you specify what parts of the site to export. Upload can be troublesome sometimes, but if you ftp the .wpress file to `/wp-content/ai1wm-backups/` you can import from the backup instead of uploading through the plugin interface.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "plugins, migration" }
Get last element from wpdb as a string I need some help in getting single string from wpdb instead od array. The below code should return child post number. It will always return array with single element. global $wpdb; $store = wp_get_current_user(); $store_id = $store->ID; $par_order = $reservation->transaction_id; $sql = "SELECT ID FROM " . $wpdb->prefix . "posts WHERE post_type = 'shop_order' AND post_parent = " . $par_order . " AND post_author = " . $storer_id; $sub_orders = $wpdb->get_results($sql);
Okay, I figured it out: global $wpdb; $par_order = $reservation->transaction_id; $store = wp_get_current_user(); $store_id = $store->ID; $sql = "SELECT ID FROM $wpdb->posts WHERE post_type = 'shop_order' AND post_parent = $par_order AND post_author = $store_id"; $sub_orders = $wpdb->get_var($wpdb->prepare($sql,$seller_id)); thank you @czerspalace for the clue
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wpdb" }
Never Enqueued Stylehsheet I never Enqueued the main stylesheet I'm using on my Wordpress site in the functions.php doc. I just uploaded the stylesheet to the site. Everything works, but I now want to dequeue the stylesheet on a specific page template. How would I go about enqueueing the stylesheet? I'm not sure why my stylesheet works even though I haven't enqueued it. Any help would be much appreciated. ![enter image description here](
`style.css` is a requirement for any theme. Therefore you cannot dequeue it. You can however have a blank (except for the comments) style.css and enqueue another stylesheet for certain templates. To do so you would use `wp_enqueue_scripts()` like so : function my_enqueue_style() { if ( is_front_page() ) { wp_enqueue_style( 'mystyle', get_stylesheet_directory_uri() . '/mystyle.css' ); } } add_action( 'wp_enqueue_scripts', 'my_enqueue_style' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp enqueue style, css" }
exclude multiple terms using get_terms() function I am using this function to filter category terms from a calendar: $terms = get_terms( TribeEvents::TAXONOMY, array( 'orderby' => 'name', 'order' => 'ASC','exclude' => array(77)) ); echo '<li>Category:</li>'; foreach ( $terms as $term ) { echo '<li><a href="'.$url.'?tribe_eventcategory='.$term->term_taxonomy_id.'">'.$term->name.'</a></li>'; } I need to exclude event category ID 71 too. How can I do that?
With `get_terms()`, the `exclude` parameter takes an array of term IDs, so just add the second term to the array: $terms = get_terms( TribeEvents::TAXONOMY, array( 'orderby' => 'name', 'order' => 'ASC', 'exclude' => array( 77, 71 ), ) ); echo '<li>Category:</li>'; foreach ( $terms as $term ) { echo '<li><a href="'.$url.'?tribe_eventcategory='.$term->term_taxonomy_id.'">'.$term->name.'</a></li>'; }
stackexchange-wordpress
{ "answer_score": 11, "question_score": 5, "tags": "php, functions, categories" }
No srcset for hard-cropped thumbnails I am using hard-crop on featured images like this : add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size ( 635, 200, true ); I have no other plugin installed, not even Jetpack. No matter how large the image I upload wordpress won't add srcset for my cropped featured images. **_EDIT_** : The problem seems to be with hard crop feature because the srcset shows correctly on any other image posted in article (from media for example). If I deactivate the hard crop the srcset shows correctly on the thumbnails too.
To show a srcset, there must be multiple image sizes of the same aspect ratio. When you set your thumbnail to hard crop without creating any other image sizes you are ensuring that there won't be a srcset. You might find my answer here helpful. Briefly, in your case, adding this line: add_image_size ( 'double-size', 1270, 400, true ); ... will make a srcset with both the cropped sizes when you upload a fresh image larger than 1270x400.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "images, thumbnails, post thumbnails" }
get all posts associated with a custom taxonomy Looks like the advanced tax query options in WordPress does not allow the following query: > Get me the most recent posts but only those posts that have at least one term under the taxonomy I'm interested in ( here the key thing is "any term" under that taxonomy would be OK to qualify that post to be part of the results ) The taxonomy query samples I've seen so far does things like this > Get me the most recent posts but only those posts that have term A and term B of that taxonomy. ( Here, the limiting thing is that I must specify the terms I want and I do not seem to have an option to say, "all terms" or "any term" Am I correct in saying that what I want is not possible with the current query params?
You can do what you want with the `tax_query` parameter since version 4.1, use `EXISTS` as the operator parameter in your tax query. $args = array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'mytax', 'operator' => 'EXISTS' ), ), ); $query = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp query, custom taxonomy, advanced taxonomy queries" }
Proper use of internationalization Regarding internationalization which of the two would be the proper correct way to process the translation. echo '<p>' . esc_html__( 'Lorem ipsum dolor sit amet, consectetur adipisicing', 'textdomain' ) . '</p>'; or printf( '<p>%1$s</p>', esc_html__( 'Lorem ipsum dolor sit amet, consectetur adipisicing', 'textdomain' ) ); And if i need to add wrap the following within p tags i would just need to add the p tags as allowed HTML tags. As shown below printf( wp_kses( __( '<p>Ready to publish your first post? <a href="%1$s">Get started here</a>.</p>', 'maker_' ), array( 'a' => array( 'href' => array() ), 'p' => array() ) ), esc_url( admin_url( 'post-new.php' ) ) );
The two are exactly the same but I would go for the first one: * Easier to read * No interpolation, keep interpolation for variables And, including the tags inside the format is making things more complicated, I can think of designers being tempted to use more tags if they see you are using them.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, translation, localization, wp kses" }
XML-RPC errors they know my username? I have noticed a lot of XML-RPC authentication failures to my blog site. This can be normal and idiots attempting to crack a wordpress site but what is worrying is that the username being shown in the log is actually my admin username (I'm not using admin and I actually have a username that no one should be able to guess). What's going on?
user names in wordpress in general are not considered as being a secret and there are all kinds of ways to get or guess them. Passwords are a secret, always use a strong one
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "security, xml rpc" }
Shortcodes on my website stops working after theme update Hi I am using pagelines theme on my website and have updated the theme today. I am showing a download form here on the below page using a shortcode < The shortcode on the above page does not work any more and other short codes for post-content id=x works How can I fix this issue?
most likely your `[download_ebook_lead_form ret_url=""]` shortcode was defined in functions.php in your theme parent folder, and during update the file was somehow replaced with new one. If you have backup of previous version of your theme check its functions.php and look for `add_shortcode( 'download_ebook_lead_form'...)`. If you find it there just copy entire function to functions.php in updated theme.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, themes, shortcode" }
Add script to page at certain location in wordpress Generally we use the `wp-equeue-script` to add scripts to the page inside the header or the body section, but how about if I want to insert a script file at a certain location (like at the middle of the page)? Furthermore, is it possible to generate dynamic scripts? For example ` which will return different scripts based no the query?
To answer your first question, you can always add a `<script>` tag inside your template files wherever you like, would that solve it? Or alternatively add a function `<?php add_my_script(); ?>` somewhere in your template files which you put in `functions.php` and does some more checks to determine if you want a script there on that location and add it. However, do you really need it at a certain location in your page? It should not make a difference where you put the script, because you can wrap your functionality inside a function, and only run it when you call the function. To answer your second question, yes you can, it's been answered before. < So don't call a .js file, call a .php file that renders your script. just make sure the to use a `header("Content-Type: application/javascript");` and whatever logic you want there
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "javascript, wp enqueue script" }
Woocommerce make <div> appear when items added to cart This should be simple but for whatever reason it is not working for me. Here is my PHP: <?php if (sizeof( $woocommerce->cart->cart_contents ) !== 0) { echo '<p>hello there</p>'; } ?> Basically I want the header to display some custom HTML I have created after an item is added to the cart. This code isn't working correctly though. Can anyone show me where I am going wrong?
Try this; it's from the WC function that displays a link to the cart when there are items in the cart. The differences are the use of `global` and the `> 0` operand: global $woocommerce; if ( sizeof( $woocommerce->cart->cart_contents) > 0 ) : echo '<p>hello there</p>'; endif;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to enable the theme editor cap for an editor role? I am trying to add/enable the theme editor for the _editor_ role. The _editor_ role by default doesn't have the option to manage theme options, so I addded this to functions.php: // get the the role object $role_object = get_role( 'editor' ); // add $cap capability to this role object //$role_object->add_cap( 'edit_theme_options' ); $role_object->add_cap( 'manage_options' ); But still, I don't see the theme editor option. In the end, I want the theme editor to be the only submenu option. Any suggestions?
The `edit_themes` capability is what allows access to Appearance > Theme Editor: function wpse243341_modify_editor_role() { $role = get_role( 'editor' ); $role->add_cap( 'edit_themes' ); } add_action( 'admin_init', 'wpse243341_modify_editor_role');
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "users, user roles, editor, capabilities" }
Can the qTranslateX-Plugin translate non-article text? I started using the qTranslateX plugin for a bilingual Wordpress site, and I am very happy with how it translates posts and pages. However, there is some text on the site that was entered as part of a widget, and I need it to be bilingual too. Can this be done? If not with qTranslateX, what are my options?
You can try like adding content in this format in Widget title/text content. [:en]My English Title[:fr]My French Title and on echoing this.. q-translate will make them work .
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets, translation, multi language, localization, plugin qtranslate" }
How to unset fields in woocommerce product quick edit? How to unset\hide fields in woocommerce product quick edit, like tags, date, etc without modifying woocommerce plugin core?
You can refer this answer to answer to hide the quick edit functionality Remove specific items from Quick Edit menu of a Custom Post Type? Instead of `gallery` you can use `product`. You can write the codes in your theme's or child theme to hide the quick edit section.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic, quick edit" }
Theme url in all plugin pages I am developing a plugin. In my ranking.php, I have a form with the action called detailpage.php, which also resides with ranking.php. I want to add the activated themes header and footer to table_detail.php, but it is throwing errors (e.g " _Call to undefined function get_theme_root_uri()_ ") How can I achieve this functionality (without the error)? This is my ranking.php form: <form id="detail_form" method="POST" action=" target="_blank"> <input type="text" name="detail_data" id="detail_data"> <input type="submit"> </form>
By adding wp-blog-header.php in the files that reside outside wordpress you can use all the wordpress functionality. Thanks to the answer found here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, plugin development" }
Use WordPress page instead of post type archive Sorry if this is a duplicate – I can't find an answer. How do I rewrite a custom post type archive page to a 'man-made' WordPress page? For example: * Single page: ` * Archive page: ` I want ` to rewrite to ` Can I just do this with htaccess and what would the syntax be? (I'm not good at htaccess!) This does not work: RewriteRule ^cool-post-type\/\?$ /about-cool-post-types [L] Or do I have to do this in the WordPress source code? I don't want to!
This one's actually pretty easy. When you declare your post type using register_post_type, you need to add a new argument for 'has_archive'. So you'll add in something to the effect of: 'has_archive' => 'about-cool-post-types' Then, go to your Settings > Permalinks to flush them and it should work. I tested it locally, and this seems to be the way to automatically generate your archive page at a different URL. Then, you should be able to create a page at the CPT's slug.
stackexchange-wordpress
{ "answer_score": 17, "question_score": 15, "tags": "custom post types" }
Which function crops images in wordpress? I want to modify wordpress's core files to get a desired result for cropping and saving uploaded images. However, i can't find the function that handles the uploaded images and crops, renames and saves them. I thought this function may have something to do with thumbnails :`wp_generate_attachment_metadata` Can anyone help me which file and function does this? Thank you
The image goes through multiple processes for the thumbnail to be generated. Take a look into the `WP_Image_Editor` class in the `wp-includes/class-wp-image-editor.php`. This class handles cropping, resizing, etc. There is a public function inside this class, named `crop()`. This might be what you are after. However, the actual resizing is handled by the function `multi_resize()`, which generates thumbnails for each uploaded image.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, images" }
How to make a local "scroll to ID" on post? I am trying to figure out the best way to do something similar with < ![enter image description here]( I understand that I have to use scrollspy and work on couple jQuery line for "scroll-to" thing and also working with affix, I have no problem doing that on static page. On the post of WordPress, I want to have an "index" where the reader can jump from one section to another (exactly like the getbootstrap page). What I don't know is how to generate this on the post dynamically, since * Each post will have a different index name * Each post will have a different amount of index. * Each post will have a different id name. I am looking for using Advance Custom Field. Anyone has an experience on this or can help?
Would a table of contents plugin like < work for your case?
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "posts, custom field, advanced custom fields" }
Open popup automatically when navigate to the page id Hi I have a custom link on menu url : #contact, and use plugin to display popup like this jQuery('a[href="#contact"]').magnificPopup({ }); So when im on my page I click on it and it shows popup. but when I'm on another website (can modify) I want to navigate to this site and open popup automatically, is it possible? please help me. I try to navigate my site to : site.com/#contact but it doesnt show anything.
What you can do is on document ready you can check your url and based on if #contact is there on not, show popup. Something like: jQuery(document).ready(function () { var type = window.location.hash.substr(1); if(type == 'contact'){ //show popup } } Note: Check for syntax. Code not tested or tried.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "html" }
Facebook Share Permalink Javascript href Hi I am trying to get a facebook share button to share the current post permalink page to no avail. Anyone help? <?php var $perma = '<?= get_the_permalink(); ?>';?> <a href="javascript:fbShare('<?php echo $perma ?>', 'FB Share', 'Facebook share popup', '<?php echo $perma ?>', 520, 350)">Share</a> JS function fbShare(url, title, descr, image, winWidth, winHeight) { var winTop = (screen.height / 2) - (winHeight / 2); var winLeft = (screen.width / 2) - (winWidth / 2); window.open(' + title + '&p[summary]=' + descr + '&p[url]=' + url + '&p[images][0]=' + image, 'sharer', 'top=' + winTop + ',left=' + winLeft + ',toolbar=0,status=0,width=' + winWidth + ',height=' + winHeight); }
All good I have figured it out <a href="javascript:fbShare('<?php echo the_permalink(); ?>', 'FB Share', 'Facebook share popup', '<?php echo the_permalink(); ?>', 520, 350)">
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, facebook, social sharing" }
Removing files programmatically I have a wordpress site running woocommerce. My site is extremely active. I literally sell items daily by the dozens and I am constantly adding new ones in. I understand I have to add the new ones manually, of course. But I wish there was a way that I could delete the images programmatically from the ones that I sold s that they don't clutter up the `uploads` folder. I have 33,235 images currently in there and 1290 products live. Can this be done via `functions.php` file? or `htaccess` file? or perhaps a plugin you know about? Thanks in advance
If you want to remove the images from folder, There is a two way to remove image 1) Remove by manually 2) Remove by using plugin. **1) Using Plugin** I suggest you that can try the Image Cleanup plugin and it's the best, but still good to make a backup first. There is an another one plugin available to delete un used images DNUI. DNUI plugin will search image from the database and delete all unused images making space in your server and clean up the database from all them. **2) Manually** You can also search through your Media Library for images which are unattached to posts and pages to delete them manually. ![enter image description here]( go to Media > Library and click the Unattached link which will display all images that may be displayed on other parts of your site or simply not used. **It’s advisable to take a backup of your uploads folder & database before deleting any images stored in these directories and data in your db.**
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, woocommerce offtopic, htaccess" }
See Scripts used by Page I use chrome and have used developer tools inspector in Chrome many times in the past to see which scripts a page is using, but in the latest version of Chrome, there is no 'Resources' tab in the inspector. How do I see which scripts are enqueued on a given page via inspector now?
Why can't you check loaded scripts in source code? All the scripts will be listed there, unless you minified them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "wp enqueue script" }
How to track a users last visited page? There are certain pages with a certain template in my wordpress site that all of them lead to a single page(S). I want the content of the single page(S) to change based on where the user has came from. In other words, I want to be able to detect that from which page the user has come to that single page(S). Is there an easy way to do this? I'm not an advance user, just creating my first wordpress theme :). Thanks
As far I've researched there are two ways in my mind to achieve this and they are- 1. **Database:** Save the value of the current page ID in the database for the user and continuously update it. That way you can get the last visited page by a user. **You can store multiple page visit stat as serialized data in database.** Though it is kinda performance reducer but it's effective. And it saves the data which you can use later for any kinda query. 2. **Session:** You can also use `session` to store the previous page ID and this way you can get the last visited page. At `session` destruction you can get the data by `session_set_save_handler` Hope those above ways are gonna help you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, themes, pages" }
How to reference an existing css content-based icon, within my admin menu hook Within WordPress 4.6.1, I really like the thumbtack icon that is being used in the admin menus. This is the thumbtack icon (generated in CSS) that I am referring to... ![enter image description here]( I'm currently using the WordPress API to generate my own menu with the following admin menu hook... add_menu_page('Cool Plugin Page', 'Cool Plugin', 'manage_options', 'my_main_menu','my_main_plugin_page', plugins_url('/images/thumbtack-icon.jpg',__FILE__)); So how do I replace the `plugins_url()` portion within my hook with the same css thumbtack that WordPress is using for the other menu section? When I view source through developer tools, I see it looks like this... .dashicons-admin-post:before, .dashicons-format-standard:before { content: "\f109"; }
Wordpress uses Dashicons. Basically you would replace your code with this: `add_menu_page('Cool Plugin Page', 'Cool Plugin', 'manage_options', 'my_main_menu','my_main_plugin_page', 'dashicons-admin-post', '');`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin menu, admin css" }
When do i need to get permalink structure of a specific post? As already known that the function `the_permalink` echos out the URL for current post in the loop, while the function `get_permalink` returns the permalink for a specific post using `$post_id`, but `get_permalink` has the `$leavename` that allows return the URL structure of a post to finally (for example) get a URL that looks like this ` So, When do i may need such output? Please notice the output: <?php $x= get_permalink($post_id, true); echo $x; //output // ?> If i turned the `$leavename` to `false` i will already have the post name in the URL. So again , What makes me turn it to `true`
It's used in admin context to display URL previews. When you change the slug of a post, the code that enables that mechanism is getting the format of the URL via that function.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks" }
How do i wrap woocomerce attribute in list? I want to wrap a particular woocomerce attribute value in a list. e.g. include is a attribute i want to wrap it value in a list. i have attached a image for your reference ![enter image description here](
global $product; $attributes = $product->get_attribute( 'pa_attribute_name' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, woocommerce offtopic, list, customization" }