qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
251,877 |
<p>Thanks for any help.</p>
<p>I am in a custom post (not an archive) with a taxonomy.
And I'd like to display : </p>
<ul>
<li>some other custom posts</li>
<li>with this <b>current taxonomy</b></li>
</ul>
<p>Doesn't seems so hard but for me it does...
I didn't find the right way to use the term of my tax in the query...</p>
<p>Here is (one of) my try :</p>
<pre>
$terms = wp_get_post_terms( $post->ID, 'identite'); // to get my taxonomy
foreach ( $terms as $term ) {
echo "$term->slug"; // just for test - ok
$args = array(
'post_type' => 'example',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'identite',
'field' => 'ID',
'terms' => $terms
)
),
);// end args
$query = new WP_Query( $args);
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Little pray, but doesn't work
}//end of while
}
</pre>
<p>I obtain this error message :
<em>Object of class WP_Term could not be converted to int in</em></p>
<p>Any idea to convert my object and make it readable ?
Thanks a lot</p>
<p><em>(edit : I try with the function wp_list_pluck but without success)</em></p>
|
[
{
"answer_id": 251884,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 2,
"selected": true,
"text": "<p>Try this for <code>WP_Query</code></p>\n\n<pre><code>$args = array(\n'post_type' => 'example',\n'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'identite',\n 'field' => 'ID',\n 'terms' => $term->term_id\n )\n ),\n );// end args\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>$args = array(\n'post_type' => 'example',\n'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'identite',\n 'field' => 'ID',\n 'terms' => array($term->term_id)\n )\n ),\n );// end args\n</code></pre>\n\n<p><code>$term</code> is an object and <code>tax_query</code> expects an array of id's.</p>\n\n<p>See: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters</a></p>\n"
},
{
"answer_id": 251886,
"author": "Marc-Antoine Parent",
"author_id": 110578,
"author_profile": "https://wordpress.stackexchange.com/users/110578",
"pm_score": 0,
"selected": false,
"text": "<p>You get this error message because of the way you are setting up the <code>$args</code> array. In the <code>tax_query</code>, you'll want to pass an array of all the terms ids for the current post. Also, the <code>field</code> value was incorrect (as seen in the Codex here: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">WP_Query#Taxonomy_Parameters</a>). </p>\n\n<p>The final code should look something like:</p>\n\n<pre><code><?php \n\n$terms = wp_get_post_terms( $post->ID, 'identite'); \n$terms_ids = [];\n\nforeach ( $terms as $term ) {\n $terms_ids[] = $term->term_id;\n}\n\n$args = array(\n 'post_type' => 'example',\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'identite',\n 'field' => 'term_id',\n 'terms' => $terms_ids\n )\n ),\n);\n\n$query = new WP_Query($args);\n\nif ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n\n // All the magic here\n }\n}\n</code></pre>\n"
}
] |
2017/01/09
|
[
"https://wordpress.stackexchange.com/questions/251877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110465/"
] |
Thanks for any help.
I am in a custom post (not an archive) with a taxonomy.
And I'd like to display :
* some other custom posts
* with this **current taxonomy**
Doesn't seems so hard but for me it does...
I didn't find the right way to use the term of my tax in the query...
Here is (one of) my try :
```
$terms = wp_get_post_terms( $post->ID, 'identite'); // to get my taxonomy
foreach ( $terms as $term ) {
echo "$term->slug"; // just for test - ok
$args = array(
'post_type' => 'example',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'identite',
'field' => 'ID',
'terms' => $terms
)
),
);// end args
$query = new WP_Query( $args);
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Little pray, but doesn't work
}//end of while
}
```
I obtain this error message :
*Object of class WP\_Term could not be converted to int in*
Any idea to convert my object and make it readable ?
Thanks a lot
*(edit : I try with the function wp\_list\_pluck but without success)*
|
Try this for `WP_Query`
```
$args = array(
'post_type' => 'example',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'identite',
'field' => 'ID',
'terms' => $term->term_id
)
),
);// end args
```
OR
```
$args = array(
'post_type' => 'example',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'identite',
'field' => 'ID',
'terms' => array($term->term_id)
)
),
);// end args
```
`$term` is an object and `tax_query` expects an array of id's.
See: <https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters>
|
251,890 |
<p>I've custom post "products" with standart categories and subcategories. Now I need to display a list of products on category page, that current category contains.</p>
<p>If category don't have subcategories I need to display this:</p>
<pre><code><ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
</code></pre>
<p>And if category contains sub categories display this:</p>
<pre><code><span class="subhead-title">Subcat 1</span>
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
<span class="subhead-title">Subcat 2</span>
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
</code></pre>
<p>How can I modyfy my <code>categories.php</code> to make my case done? Thanks in advance!</p>
|
[
{
"answer_id": 251892,
"author": "Marc-Antoine Parent",
"author_id": 110578,
"author_profile": "https://wordpress.stackexchange.com/users/110578",
"pm_score": 0,
"selected": false,
"text": "<p>Once you have the primary category (the one that's loaded to the categories.php template), you can use the function <code>get_term_children()</code> to get all of its children.</p>\n\n<p>It will return false or an empty array if it doesn't have children. In the example below, I assumed that your product's taxonomy is name <code>products_categories</code>. </p>\n\n<pre><code><?php \n $term = <youPrimaryTerm>;\n $term_children = get_term_children($term->term_id, 'products_categories');\n\n if(!empty($term_children)):\n foreach($term_children as $child):\n // Magic for subcategories template\n endforeach;\n else:\n // Magic in case there is no subcategories\n endif;\n?>\n</code></pre>\n\n<p>In each scenario, you will then have to create a new WP_Query using the <code>$child->term_id</code> or the <code>$term->term_id</code>.</p>\n\n<p>Note that, if a product is available in two subcategories, it will be displayed twice on the same page.</p>\n\n<p>See Codex for reference: <a href=\"https://codex.wordpress.org/Function_Reference/get_term_children\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_term_children</a></p>\n\n<p><strong>EDIT</strong></p>\n\n<p>To load the current category (when in the <code>category.php</code> template) as to replace the <code><yourPtrimaryTerm></code> from my first example, you should be able to use this snippet:</p>\n\n<pre><code><?php\n $termTitle = single_cat_title( '', false );\n $termId = get_cat_ID($termTitle);\n $term = get_term($termId, 'products_categories');\n?>\n</code></pre>\n"
},
{
"answer_id": 251916,
"author": "Mohamed Omar",
"author_id": 102224,
"author_profile": "https://wordpress.stackexchange.com/users/102224",
"pm_score": 0,
"selected": false,
"text": "<p>Try This, it should work and sure you can edit the query arguments to fit your needs. copy&past code with proper <code>html</code> tags and it should work. Check and if it worked i will try to make it more cleaner.</p>\n\n<pre><code> <?php\n $this_category = get_category($cat);\n $cats=get_categories(array('hide_empty' => '0', 'parent'=>$this_category ->cat_ID,'order'=> 'ASC','depth'=> '1'));\n\n if(!empty($cats)){\n foreach ($cats as $cat) {\n $newargs = array(\n 'tax_query' => array(\n array(\n 'taxonomy' => 'category',\n 'field' => 'name',\n 'terms' => $cat->name,\n )\n )\n );\n echo'<div>';\n echo '<span class=\"subhead-title\">'.$cat->name.'</span>';\n $nopostsparent= new wp_query( $newargs );\n if ($nopostsparent->have_posts()) {\n echo '<ul class=\"cat-arc-links\">';\n while ($nopostsparent->have_posts() ){\n $nopostsparent->the_post();\n echo'<li><a href=\"'. get_permalink() .'\" class=\"product-link\">'.get_the_title().'</a></li>';\n }\n wp_reset_query();\n echo '</ul></div>';\n }\n }\n }else{\n $newargs = array(\n 'tax_query' => array(\n array(\n 'taxonomy' => 'category',\n 'field' => 'name',\n 'terms' => $this_category->name,\n )\n )\n );\n $nopostsparent= new wp_query( $newargs );\n if ($nopostsparent->have_posts()) {\n echo '<ul class=\"cat-arc-links\">';\n while ($nopostsparent->have_posts() ){\n $nopostsparent->the_post();\n echo'<li><a href=\"'. get_permalink() .'\" class=\"product-link\">'.get_the_title().'</a></li>';\n }\n wp_reset_query();\n echo '</ul></div>';\n }\n }\n ?>\n</code></pre>\n"
},
{
"answer_id": 252211,
"author": "Saiful Islam",
"author_id": 83449,
"author_profile": "https://wordpress.stackexchange.com/users/83449",
"pm_score": 0,
"selected": false,
"text": "<p>Got some ideas for your requirement. Check below code... don't forgot to update taxonomy and custom post type bellow code .</p>\n\n<pre><code>$parent= get_queried_object()->term_id;\n$taxonomy = get_categories('child_of='.$parent. '&hide_empty=0&echo=0&taxonomy=custom_taxonomy');\n\nif(count($taxonomy) > 0){\n\n foreach ( $taxonomy as $row ) { \n echo '<span>'.$row->name.'</span>';\n if(count($child)==$i){\n echo '<ul class=\"cat-arc-links\">';\n $args=array( 'post_type' => 'custom_post','posts_per_page'=>1,'tax_query' => array( array('taxonomy' => 'custom_taxonomy','terms' =>$row->term_id, 'field' => 'id' )) );\n $second_query = new WP_Query( $args );\n if ($second_query->have_posts()) :\n while ($second_query->have_posts()) : $second_query->the_post();\n echo ' <li><a href=\"'.get_permalink(get_the_ID()).'\" class=\"product-link\">'.get_the_title().'</a></li>';\n endwhile; \n endif; wp_reset_query();\n echo '</ul>'; \n }\n }\n\n}else{\n echo '<ul class=\"cat-arc-links\">';\n $args=array( 'post_type' => 'custom_post','posts_per_page'=>1,'tax_query' => array( array('taxonomy' => 'custom_taxonomy','terms' =>get_queried_object()->term_id, 'field' => 'id' )) );\n $second_query = new WP_Query( $args );\n if ($second_query->have_posts()) :\n while ($second_query->have_posts()) : $second_query->the_post();\n echo ' <li><a href=\"'.get_permalink(get_the_ID()).'\" class=\"product-link\">'.get_the_title().'</a></li>';\n endwhile; \n endif; wp_reset_query();\n echo '</ul>'; \n\n}\n</code></pre>\n"
},
{
"answer_id": 252221,
"author": "Alex P.",
"author_id": 48584,
"author_profile": "https://wordpress.stackexchange.com/users/48584",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks to all! Here is my solution which worknig well</p>\n\n<pre><code><?php \n\n$cat = get_query_var('cat');\n\n$categories = get_categories('parent='.$cat.''); \n\nif(isset($categories) && !empty($categories)){ \n\n foreach ($categories as $category) { ?>\n\n <span class=\"subhead-title\"><?php echo $category->name; ?></span>\n\n <?php $prods = new WP_query(); $prods->query('post_type=products&cat=' . $category->cat_ID . ''); ?>\n <?php if($prods->have_posts()) { ?> <ul class=\"cat-arc-links\"> <?php while ($prods->have_posts()) { $prods->the_post(); ?>\n\n <li><a href=\"<?php the_permalink(); ?>\" class=\"product-link\"><?php the_title(); ?></a></li>\n\n\n <?php } ?> </ul> <?php } ?>\n\n<?php }\n\n}\nelse \n{\n global $query_string; // basic query parameters\n query_posts( $query_string.'&post_type=products'); // basic query + self parameters \n\n if( have_posts() ) { ?> <ul class=\"cat-arc-links\"> <?php while( have_posts() ){ the_post(); ?>\n\n <li><a href=\"<?php the_permalink(); ?>\" class=\"product-link\"><?php the_title(); ?></a></li>\n\n<?php } /* end of while */ wp_reset_query(); ?>\n</ul>\n <div class=\"navigation\">\n <div class=\"next-posts\"><?php next_posts_link(); ?></div>\n <div class=\"prev-posts\"><?php previous_posts_link(); ?></div>\n </div>\n\n<?php\n } \n else \n echo \"<h2>No entries.</h2>\";\n}\n?>\n</code></pre>\n"
}
] |
2017/01/10
|
[
"https://wordpress.stackexchange.com/questions/251890",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48584/"
] |
I've custom post "products" with standart categories and subcategories. Now I need to display a list of products on category page, that current category contains.
If category don't have subcategories I need to display this:
```
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
```
And if category contains sub categories display this:
```
<span class="subhead-title">Subcat 1</span>
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
<span class="subhead-title">Subcat 2</span>
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
```
How can I modyfy my `categories.php` to make my case done? Thanks in advance!
|
Thanks to all! Here is my solution which worknig well
```
<?php
$cat = get_query_var('cat');
$categories = get_categories('parent='.$cat.'');
if(isset($categories) && !empty($categories)){
foreach ($categories as $category) { ?>
<span class="subhead-title"><?php echo $category->name; ?></span>
<?php $prods = new WP_query(); $prods->query('post_type=products&cat=' . $category->cat_ID . ''); ?>
<?php if($prods->have_posts()) { ?> <ul class="cat-arc-links"> <?php while ($prods->have_posts()) { $prods->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" class="product-link"><?php the_title(); ?></a></li>
<?php } ?> </ul> <?php } ?>
<?php }
}
else
{
global $query_string; // basic query parameters
query_posts( $query_string.'&post_type=products'); // basic query + self parameters
if( have_posts() ) { ?> <ul class="cat-arc-links"> <?php while( have_posts() ){ the_post(); ?>
<li><a href="<?php the_permalink(); ?>" class="product-link"><?php the_title(); ?></a></li>
<?php } /* end of while */ wp_reset_query(); ?>
</ul>
<div class="navigation">
<div class="next-posts"><?php next_posts_link(); ?></div>
<div class="prev-posts"><?php previous_posts_link(); ?></div>
</div>
<?php
}
else
echo "<h2>No entries.</h2>";
}
?>
```
|
251,898 |
<p>In a plugin I have a payment form that needs to be submitted (via the action= attribute) to a .php file, also located in my plugin directly. After some research, it seems like the "wordpress way" to call up individual plugin files is to actually use custom queries on index.php instead. I've done so with the below code, and it's working, however the code in question simply needs to process the form and then redirect the user to a confirmation page, I don't need to display anything. Right now it seems like it's actually loading the index.php template, which seems like a waste.</p>
<p>Am I going about this correctly? If not, how should I do this instead?</p>
<pre><code>//Register our custom request hook
function tps_space_rental_query_vars($vars) {
$vars[] = 'tps-rent-space';
return $vars;
}
add_filter('query_vars', 'tps_space_rental_query_vars');
//This will allow us to process our payment form the wordpress way
function tps_payment_parse_request($wp) {
if (array_key_exists('tps-rent-space', $wp->query_vars)
&& $wp->query_vars['tps-rent-space'] == 'chargeform') {
// process the request, just testing for now
echo 'This request happened!';
}
}
add_action('parse_request', 'tps_payment_parse_request');
</code></pre>
|
[
{
"answer_id": 251945,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 2,
"selected": true,
"text": "<p>the easiest way is using init action hook</p>\n\n<pre><code>add_action(\"init\", \"your_form_handler_action\");\nfunction your_form_handler_action(){\n if( isset( $_REQUEST[\"action\"] ) && $_REQUEST[\"action\"] == \"your_action_name\" ) {\n echo \"Response!!!\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 251950,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress has a general POST/GET request endpoint, using the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_post_(action)\" rel=\"nofollow noreferrer\">admin_post_(action)</a> to hook your code to an action, similar to how WordPress handles AJAX requests. Use <code>admin_url( 'admin-post.php' )</code> to output the URL.</p>\n"
}
] |
2017/01/10
|
[
"https://wordpress.stackexchange.com/questions/251898",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23492/"
] |
In a plugin I have a payment form that needs to be submitted (via the action= attribute) to a .php file, also located in my plugin directly. After some research, it seems like the "wordpress way" to call up individual plugin files is to actually use custom queries on index.php instead. I've done so with the below code, and it's working, however the code in question simply needs to process the form and then redirect the user to a confirmation page, I don't need to display anything. Right now it seems like it's actually loading the index.php template, which seems like a waste.
Am I going about this correctly? If not, how should I do this instead?
```
//Register our custom request hook
function tps_space_rental_query_vars($vars) {
$vars[] = 'tps-rent-space';
return $vars;
}
add_filter('query_vars', 'tps_space_rental_query_vars');
//This will allow us to process our payment form the wordpress way
function tps_payment_parse_request($wp) {
if (array_key_exists('tps-rent-space', $wp->query_vars)
&& $wp->query_vars['tps-rent-space'] == 'chargeform') {
// process the request, just testing for now
echo 'This request happened!';
}
}
add_action('parse_request', 'tps_payment_parse_request');
```
|
the easiest way is using init action hook
```
add_action("init", "your_form_handler_action");
function your_form_handler_action(){
if( isset( $_REQUEST["action"] ) && $_REQUEST["action"] == "your_action_name" ) {
echo "Response!!!";
}
}
```
|
251,908 |
<p>So I've been working in Wordpress lately with Ajax and I managed to get some stock data into my site from my database. However, I am now trying to use Ajax to load Wordpress posts into my left sidebar, which requires the use of Wordpress functions and it seems as if I am not doing this properly.get_option() shows NULL on this.</p>
<p>JS</p>
<pre><code> url:"<?php echo get_template_directory_uri(); ?>/sendContactForm.php",//request URL
type:"POST",//Request type GET/POST
data: $(_this).serialize()
</code></pre>
<p>PHP(sendContactForm.php)</p>
<pre><code>$result = new stdClass();
$from = $_REQUEST['email'];
$message = $_REQUEST['message'];
$sender = $_REQUEST['email'];
$result->message = $message;
$result->subject = $_REQUEST['name'] . " send you a message";
$result->to = "get_option('admin_email');
$result->to = "get_option('admin_email'); showing NULL
</code></pre>
|
[
{
"answer_id": 251911,
"author": "magicroundabout",
"author_id": 10046,
"author_profile": "https://wordpress.stackexchange.com/users/10046",
"pm_score": 3,
"selected": true,
"text": "<p>I confess that I'm slightly confused by how your sending email function loads posts into your sidebar...the code does not seem to be doing the thing that you described.</p>\n\n<p>Are you loading WordPress in sendContactForm.php? Is what you've shown here the only code in sendContactForm.php?</p>\n\n<p><code>get_option()</code> is a WordPress function, so you need to load WordPress to do this. This is usually done by putting something at the top of your php file like:</p>\n\n<p><code>require('../../../wp-load.php');</code></p>\n\n<p>But that's a bit hacky.</p>\n\n<p>The proper way to do AJAX in WordPress is to send your POST request to <code>/wp-admin/admin-ajax.php</code> with an parameter like <code>action=sendContactForm</code> and then create an action hook like this:</p>\n\n<pre><code>add_action('wp_ajax_sendContactForm', 'my_email_function');\nadd_action('wp_ajax_nopriv_sendContactForm', 'my_email_function');\n\nfunction my_email_function() {\n // process request here\n wp_die();\n}\n</code></pre>\n\n<p>Read more about this at: <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n"
},
{
"answer_id": 251912,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the email address in the WordPress code and add it to a data attribute like: </p>\n\n<pre><code><div class=\"container\">\n <div class=\"whatever-your-class\" data-email=\"<?php echo get_option('admin_email'); ?>\">\n </div>\n</div>\n</code></pre>\n\n<p>And then in your AJAX code, something like this: </p>\n\n<pre><code>$post = $(this);\n$.ajax({\n url: \"test.php\", // where you are posting to\n type: \"GET\",\n data: { email: $($email).attr(\"data-email\") }, \n success: function(response) {\n alert(response); \n }\n}); \n</code></pre>\n\n<p>Does that make sense? You are echoing the email address on to your page template and then using jQuery to grab it and place it in your AJAX call. It's messy but it should work. </p>\n"
}
] |
2017/01/10
|
[
"https://wordpress.stackexchange.com/questions/251908",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101257/"
] |
So I've been working in Wordpress lately with Ajax and I managed to get some stock data into my site from my database. However, I am now trying to use Ajax to load Wordpress posts into my left sidebar, which requires the use of Wordpress functions and it seems as if I am not doing this properly.get\_option() shows NULL on this.
JS
```
url:"<?php echo get_template_directory_uri(); ?>/sendContactForm.php",//request URL
type:"POST",//Request type GET/POST
data: $(_this).serialize()
```
PHP(sendContactForm.php)
```
$result = new stdClass();
$from = $_REQUEST['email'];
$message = $_REQUEST['message'];
$sender = $_REQUEST['email'];
$result->message = $message;
$result->subject = $_REQUEST['name'] . " send you a message";
$result->to = "get_option('admin_email');
$result->to = "get_option('admin_email'); showing NULL
```
|
I confess that I'm slightly confused by how your sending email function loads posts into your sidebar...the code does not seem to be doing the thing that you described.
Are you loading WordPress in sendContactForm.php? Is what you've shown here the only code in sendContactForm.php?
`get_option()` is a WordPress function, so you need to load WordPress to do this. This is usually done by putting something at the top of your php file like:
`require('../../../wp-load.php');`
But that's a bit hacky.
The proper way to do AJAX in WordPress is to send your POST request to `/wp-admin/admin-ajax.php` with an parameter like `action=sendContactForm` and then create an action hook like this:
```
add_action('wp_ajax_sendContactForm', 'my_email_function');
add_action('wp_ajax_nopriv_sendContactForm', 'my_email_function');
function my_email_function() {
// process request here
wp_die();
}
```
Read more about this at: <https://codex.wordpress.org/AJAX_in_Plugins>
|
252,004 |
<p>I'm attempting to change the "← Back to sitename" text on the wp-login.php page using gettext but not having much luck.</p>
<p>No matter what I try it doesn't seem to want to work, although I've had success changing the "Lost your password?" text using the same method.</p>
<p>Here is my latest snippet</p>
<pre><code>function custom_login_text ( $text ) {
if (in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) )) {
if ($text == '&larr; Back to %s'){$text = 'Test';}
return $text;
}
}
add_filter( 'gettext', 'custom_login_text' );
</code></pre>
<p>I've also tried directly using <code>← Back to Site Name</code> but that didn't work either. Am I missing something?</p>
<p>Any tips would be appreciated.</p>
|
[
{
"answer_id": 251952,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 1,
"selected": false,
"text": "<p>It's usually a permissions error. We used to have these issues on our older servers. As a general rule for file permissions, you should never allow a folder to be \"777\" (Read/Write/Execute), but the uploads folder on this server, unfortunately, might need it. If you don't know what I'm talking about, please take a read through of <a href=\"https://codex.wordpress.org/Changing_File_Permissions\" rel=\"nofollow noreferrer\">Wordpress' guide to Changing File Permissions</a>.</p>\n"
},
{
"answer_id": 253375,
"author": "Christine",
"author_id": 111424,
"author_profile": "https://wordpress.stackexchange.com/users/111424",
"pm_score": 0,
"selected": false,
"text": "<p>This is actually probably an issue within the database file wp_options having the upload directory incorrectly listed. Go into your database, go to wp_options, and make sure the upload_path is blank. </p>\n"
},
{
"answer_id": 287342,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 0,
"selected": false,
"text": "<p>If you have SSH access, do the following.</p>\n\n<ol>\n<li>cd into your www folder on your server. Usually /var/www/html</li>\n<li>sudo chown -R www-data:www-data site-folder-name</li>\n</ol>\n\n<p>If you don't have access to the console, you should contact your hosting service provider and ask them to do it in your stead.</p>\n\n<p>Good luck :)</p>\n"
}
] |
2017/01/10
|
[
"https://wordpress.stackexchange.com/questions/252004",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12238/"
] |
I'm attempting to change the "← Back to sitename" text on the wp-login.php page using gettext but not having much luck.
No matter what I try it doesn't seem to want to work, although I've had success changing the "Lost your password?" text using the same method.
Here is my latest snippet
```
function custom_login_text ( $text ) {
if (in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) )) {
if ($text == '← Back to %s'){$text = 'Test';}
return $text;
}
}
add_filter( 'gettext', 'custom_login_text' );
```
I've also tried directly using `← Back to Site Name` but that didn't work either. Am I missing something?
Any tips would be appreciated.
|
It's usually a permissions error. We used to have these issues on our older servers. As a general rule for file permissions, you should never allow a folder to be "777" (Read/Write/Execute), but the uploads folder on this server, unfortunately, might need it. If you don't know what I'm talking about, please take a read through of [Wordpress' guide to Changing File Permissions](https://codex.wordpress.org/Changing_File_Permissions).
|
252,027 |
<p>I want to sanitize the title of a specific custom post type. I've managed to create a filter which sanitizes the titles. How ever It affects rest of the post types as well. After a lot of search I've managed to write an action which enables me to execute functions on specific pages on the admin panel. But I'm incapable of firing filters in actions.</p>
<p>So any help is appreciated. </p>
<pre><code>function check_cpt( $hook_suffix ){
$cpt = 'custom_post_type';
if( in_array($hook_suffix, array('post-new.php', 'post.php') ) ){
$screen = get_current_screen();
if( is_object( $screen ) && $cpt == $screen->post_type ){
echo'I'm only visible on custom post type';
die;
//add_filter( 'sanitize_title', 'url_sanitizer', 10, 3 );
//above filter doesnt work
}
}
}
add_action( 'admin_enqueue_scripts', 'check_cpt');
</code></pre>
<p>The above action works just as I intended.How ever I cannot fire the filter.
This is the filter function</p>
<pre><code>function url_sanitizer( $title, $raw_title, $context) {
$new_title = $raw_title;
$new_title = str_replace( ' ', '_', $new_title );
$new_title = str_replace( '-', '_', $new_title );
return $new_title;
}
</code></pre>
|
[
{
"answer_id": 252030,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 2,
"selected": true,
"text": "<p>you want to sanitize the title or the post_name (slug)?\n<br>\nif you want to filter post_name you can check <code>wp_unique_post_slug</code> filter or you can use the <code>wp_insert_post_data</code> filter to filter all post data before insert or update in db.</p>\n\n<pre><code>add_filter( \"wp_unique_post_slug\", \"url_sanitizer\", 10, 4 );\nfunction url_sanitizer( $slug, $post_ID, $post_status, $post_type ) {\n // get original title by $post_ID if needed eg. get_the_title($post_ID)\n if( $post_type == \"your_cpt\" ) {\n $slug= str_replace( ' ', '_', $slug);\n $slug= str_replace( '-', '_', $slug);\n }\n return $slug;\n}\n</code></pre>\n\n<p>Reference:\n<br>\n<code>wp_unique_post_slug</code> documented in <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/post.php#L3790\" rel=\"nofollow noreferrer\">wp-includes/post.php Line No. 3790</a><br>\n<code>wp_insert_post_data</code> <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data</a></p>\n"
},
{
"answer_id": 252032,
"author": "khan",
"author_id": 110654,
"author_profile": "https://wordpress.stackexchange.com/users/110654",
"pm_score": 0,
"selected": false,
"text": "<p>if you want to filter post_name you can check wp_unique_post_slug filter or you can use the wp_insert_post_data filter to filter all post data before insert or update in db.</p>\n\n<pre><code>add_filter( \"wp_unique_post_slug\", \"url_sanitizer\", 10, 4 );\nfunction url_sanitizer( $slug, $post_ID, $post_status, $post_type ) {\n // get original title by $post_ID if needed eg. get_the_title($post_ID)\n if( $post_type == \"your_cpt\" ) {\n $slug= str_replace( ' ', '_', $slug);\n $slug= str_replace( '-', '_', $slug);\n }\n return $slug;\n}\n</code></pre>\n\n<p>Reference: \nwp_unique_post_slug documented in wp-includes/post.php Line No. 3790\nwp_insert_post_data <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data</a></p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252027",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48438/"
] |
I want to sanitize the title of a specific custom post type. I've managed to create a filter which sanitizes the titles. How ever It affects rest of the post types as well. After a lot of search I've managed to write an action which enables me to execute functions on specific pages on the admin panel. But I'm incapable of firing filters in actions.
So any help is appreciated.
```
function check_cpt( $hook_suffix ){
$cpt = 'custom_post_type';
if( in_array($hook_suffix, array('post-new.php', 'post.php') ) ){
$screen = get_current_screen();
if( is_object( $screen ) && $cpt == $screen->post_type ){
echo'I'm only visible on custom post type';
die;
//add_filter( 'sanitize_title', 'url_sanitizer', 10, 3 );
//above filter doesnt work
}
}
}
add_action( 'admin_enqueue_scripts', 'check_cpt');
```
The above action works just as I intended.How ever I cannot fire the filter.
This is the filter function
```
function url_sanitizer( $title, $raw_title, $context) {
$new_title = $raw_title;
$new_title = str_replace( ' ', '_', $new_title );
$new_title = str_replace( '-', '_', $new_title );
return $new_title;
}
```
|
you want to sanitize the title or the post\_name (slug)?
if you want to filter post\_name you can check `wp_unique_post_slug` filter or you can use the `wp_insert_post_data` filter to filter all post data before insert or update in db.
```
add_filter( "wp_unique_post_slug", "url_sanitizer", 10, 4 );
function url_sanitizer( $slug, $post_ID, $post_status, $post_type ) {
// get original title by $post_ID if needed eg. get_the_title($post_ID)
if( $post_type == "your_cpt" ) {
$slug= str_replace( ' ', '_', $slug);
$slug= str_replace( '-', '_', $slug);
}
return $slug;
}
```
Reference:
`wp_unique_post_slug` documented in [wp-includes/post.php Line No. 3790](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/post.php#L3790)
`wp_insert_post_data` <https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data>
|
252,035 |
<p>I am trying to make the page have 3 posts in each row, and then after 3 columns (12 posts) show the ajax load more button. Right now only one post is showing up. I don't know how to make it correctly loop through everything. Can anyone provide help? Thanks in advance.</p>
<pre class="lang-html prettyprint-override"><code><?php
get_header();
get_template_part ('inc/carousel-food');
$the_query = new WP_Query( [
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1)
] );
if ( $the_query->have_posts() ) { ?>
<div id="ajax">
<article class="post">
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
</div>
<?php if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
}
elseif (!get_query_var('paged') || get_query_var('paged') == '1') {
echo '<p>Sorry, no posts matched your criteria.</p>';
}
wp_reset_postdata();
get_footer();
</code></pre>
<p>UPDATED</p>
<pre class="lang-html prettyprint-override"><code><?php
get_header();
get_template_part ('inc/carousel-food');
$the_query = new WP_Query( array(
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1),
'cat' => 10,
));
if ( $the_query->have_posts() ) {
// display #ajax wrapper only if we have posts
echo '<div id="ajax">';
while($the_query->have_posts()) {
$the_query->the_post(); ?>
<article <?php post_class(); ?>>
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
<?php }//end while
echo '</div>'; // close the #ajax wrapper after the post list
if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
} else { // if there are no posts
echo '<p>Sorry, no posts matched your criteria.</p>';
}//end if
get_footer();
?>
</code></pre>
|
[
{
"answer_id": 252036,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 0,
"selected": false,
"text": "<p>Your code doesn't have <code>while</code> loop</p>\n\n<pre><code>if ( $the_query->have_posts() ) {\n while($the_query->have_posts()){\n $the_query->the_post();\n //your html here\n }\n //code for load more\n}\n</code></pre>\n"
},
{
"answer_id": 252042,
"author": "Deb",
"author_id": 84431,
"author_profile": "https://wordpress.stackexchange.com/users/84431",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should mention post_type as well, like:</p>\n\n<pre><code>$the_query = new WP_Query( array(\n 'post_type' => 'yourpost_type'\n 'posts_per_page' => 12,\n 'paged' => get_query_var('paged', 1)\n) );\n</code></pre>\n"
},
{
"answer_id": 252094,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 1,
"selected": false,
"text": "<p>I just tested the following example code:</p>\n\n<pre><code><?php\n\n$the_query = new WP_Query( array(\n 'posts_per_page' => 12,\n 'paged' => get_query_var('paged', 1)\n ));\n\nif ( $the_query->have_posts() ) {\n\n // display #ajax wrapper only if we have posts\n echo '<div id=\"ajax\">';\n\n while($the_query->have_posts()) {\n $the_query->the_post(); ?>\n\n <article <?php post_class(); ?>> \n <div class=\"row\">\n <div class=\"col-md-4\"><?php the_post_thumbnail('medium-thumbnail'); ?>\n <h2><a class=\"post-title\" href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h2>\n <p class=\"post-excerpt\"><?php echo get_the_excerpt(); ?></p>\n <?php get_template_part( 'share-buttons' ); ?>\n <a class=\"moretext\" href=\"<?php the_permalink(); ?>\">Read more</a>\n <?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>\n </div>\n </div>\n </article>\n\n <?php }//end while\n\n echo '</div>'; // close the #ajax wrapper after the post list\n\n if(get_query_var('paged') < $the_query->max_num_pages) {\n load_more_button();\n }\n\n\n} else { // if there are no posts\n\n echo '<p>Sorry, no posts matched your criteria.</p>';\n\n}//end if\n\n?>\n</code></pre>\n\n<p>The <code><div id=\"ajax\"></code> should wrap around the whole post-list and not every single post, correct? Than this container should be outside the while loop!</p>\n\n<p>Also, when you not specify any post-type in the WP_Query, it defaults to \"any\" type. So make sure you want this!</p>\n\n<blockquote>\n <p>'any' - retrieves any type except revisions and types with 'exclude_from_search' set to true. </p>\n</blockquote>\n\n<p>In the <code><article></code> tag you should also use <code><?php post_class(); ?></code> instead of <code>class=\"post\"</code> to get some more and helpful classes automaticly. (including current post-type, status and category)</p>\n\n<p><strong>Update:</strong></p>\n\n<blockquote>\n <p>I've pasted the updated code above in my answer. It works at showing\n the posts. However it only showed one post in a row, so I added 2 more\n col-md-4. But now it just repeats the same post 3 times. How would I\n fix this? Also the ajax button will not appear.</p>\n</blockquote>\n\n<p>OK so, first ... the loop has nothing to do <strong>how</strong> you will show the posts on the frontend.(in a grid or just below each other) I can see you tried to add 3 <code><article></code> elements in the <code>while</code> loop. \n<strong><em>This is wrong</em></strong>, you just define the template of 1 <code><article></code> here, and all following will use the same.</p>\n\n<p>You use CSS to define how the articles will display on the frontend. So for example use a % width on the article elements to display 3 in a row.\n(100% / 3)</p>\n\n<p><em>Maybe</em> you can also use existing CSS classes. In your code I see <code><div class=\"col-md-4\"></code>, so this seems to already be a class of a grid/column system. So maybe look in the docs of the theme which you are using.\nIf that is already a class to display 3 cols in a row, maybe some CSS is overriding the width.</p>\n\n<p>Yeah, you just need 1 article element, and than style with CSS.</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252035",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101743/"
] |
I am trying to make the page have 3 posts in each row, and then after 3 columns (12 posts) show the ajax load more button. Right now only one post is showing up. I don't know how to make it correctly loop through everything. Can anyone provide help? Thanks in advance.
```html
<?php
get_header();
get_template_part ('inc/carousel-food');
$the_query = new WP_Query( [
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1)
] );
if ( $the_query->have_posts() ) { ?>
<div id="ajax">
<article class="post">
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
</div>
<?php if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
}
elseif (!get_query_var('paged') || get_query_var('paged') == '1') {
echo '<p>Sorry, no posts matched your criteria.</p>';
}
wp_reset_postdata();
get_footer();
```
UPDATED
```html
<?php
get_header();
get_template_part ('inc/carousel-food');
$the_query = new WP_Query( array(
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1),
'cat' => 10,
));
if ( $the_query->have_posts() ) {
// display #ajax wrapper only if we have posts
echo '<div id="ajax">';
while($the_query->have_posts()) {
$the_query->the_post(); ?>
<article <?php post_class(); ?>>
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
<?php }//end while
echo '</div>'; // close the #ajax wrapper after the post list
if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
} else { // if there are no posts
echo '<p>Sorry, no posts matched your criteria.</p>';
}//end if
get_footer();
?>
```
|
I just tested the following example code:
```
<?php
$the_query = new WP_Query( array(
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1)
));
if ( $the_query->have_posts() ) {
// display #ajax wrapper only if we have posts
echo '<div id="ajax">';
while($the_query->have_posts()) {
$the_query->the_post(); ?>
<article <?php post_class(); ?>>
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
<?php }//end while
echo '</div>'; // close the #ajax wrapper after the post list
if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
} else { // if there are no posts
echo '<p>Sorry, no posts matched your criteria.</p>';
}//end if
?>
```
The `<div id="ajax">` should wrap around the whole post-list and not every single post, correct? Than this container should be outside the while loop!
Also, when you not specify any post-type in the WP\_Query, it defaults to "any" type. So make sure you want this!
>
> 'any' - retrieves any type except revisions and types with 'exclude\_from\_search' set to true.
>
>
>
In the `<article>` tag you should also use `<?php post_class(); ?>` instead of `class="post"` to get some more and helpful classes automaticly. (including current post-type, status and category)
**Update:**
>
> I've pasted the updated code above in my answer. It works at showing
> the posts. However it only showed one post in a row, so I added 2 more
> col-md-4. But now it just repeats the same post 3 times. How would I
> fix this? Also the ajax button will not appear.
>
>
>
OK so, first ... the loop has nothing to do **how** you will show the posts on the frontend.(in a grid or just below each other) I can see you tried to add 3 `<article>` elements in the `while` loop.
***This is wrong***, you just define the template of 1 `<article>` here, and all following will use the same.
You use CSS to define how the articles will display on the frontend. So for example use a % width on the article elements to display 3 in a row.
(100% / 3)
*Maybe* you can also use existing CSS classes. In your code I see `<div class="col-md-4">`, so this seems to already be a class of a grid/column system. So maybe look in the docs of the theme which you are using.
If that is already a class to display 3 cols in a row, maybe some CSS is overriding the width.
Yeah, you just need 1 article element, and than style with CSS.
|
252,054 |
<p><em>(Queries are definitively an infinite source of misunderstanding...)</em></p>
<p>I try to display two types of informations in a tax archive (<code>taxonomy-artiste.php</code>) : </p>
<ol>
<li>The content of a page from a custom post (bio)</li>
<li>And after, a list of post from another custom post (works)</li>
</ol>
<p>If I understood well, it could be interesting to use pre_get_post to change the main query.
So, I set that in my <code>function.php</code>.</p>
<pre>
//Include all my CPT but the bio
function lm_exclude_bio( $query ) {
if( is_tax('artiste') && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'cpt#1', 'cpt#2'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'lm_exclude_bio' );
</pre>
<p>Ok, it works.</p>
<p>But, when I add a new query in this archive, it doesn't display the post I excepted...</p>
<pre>
$args = array( 'post_type' => 'bio', 'posts_per_page' => 1 );
// My second query for CPT 'bio'
$bio_query = new WP_Query( $args );
// The Loop
if ( $bio_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$bio_query->the_post();
// please, my custom post 'bio' !...
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
?>
</pre>
<p>Is it impossible( stupid ?) to set two queries with opposite arguments ?
Thanks for any help !</p>
|
[
{
"answer_id": 252057,
"author": "David Navia",
"author_id": 92828,
"author_profile": "https://wordpress.stackexchange.com/users/92828",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, first of all I found a misleading in your code, check the <code>while</code> part I ammended:</p>\n\n<pre><code>// The Loop\nif ( $bio_query->have_posts() ) {\n while ( $bio_query->have_posts() ) {\n $bio_query->the_post();\n // please, my custom post 'bio' !...\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n} else {\n // no posts found\n?>\n</code></pre>\n\n<p><strong>BUT</strong> I think you are messing with the queries because you're using two different ways to attack the WP database. In your first piece of code (I guess you put it into your <code>functions.php</code> file), your are interfering with the 'main query' object, but It seems you are never using it in your <code>taxonomy-artiste.php</code> file. I suggest to make something like this:</p>\n\n<pre><code><?php\n// Taxonomy-artiste.php\n\n\n/*\n * The content of a page from a custom post (bio)\n */\n\n$args = array( 'post_type' => 'bio', 'posts_per_page' => 1 );\n$bio_query = new WP_Query( $args );\n\n// The Loop\nif ( $bio_query->have_posts() ) {\n while ( $bio_query->have_posts() ) {\n $bio_query->the_post();\n the_content() // This will print the content of your bio post, stored in the global $post variable\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n} else {\n // no posts found\n}\n\n/*\n * And after, a list of post from another custom post \n */\n\n$args = array( 'post_type' => '#cpt1', 'posts_per_page' => 'put here the number of #cpt1 you want to load' );\n$other_query = new WP_Query( $args );\n\n// The Loop\nif ( $other_query->have_posts() ) {\n while ( $other_query->have_posts() ) {\n $other_query->the_post();\n the_content() // This will print the content of your other posts, stored in the global $post variable\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n} else {\n // no posts found\n}\n\n?>\n</code></pre>\n\n<p>I hope it will help you.</p>\n"
},
{
"answer_id": 252058,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 3,
"selected": true,
"text": "<p>You've added the filter <code>lm_exclude_bio</code> to <code>pre_get_posts</code>. So when you need to run another query you can remove the filter to get normal query. You can remove the filter like below-</p>\n\n<pre><code>// Here we're removing the filter first. Then we are running the query.\nremove_filter( 'pre_get_posts', 'lm_exclude_bio' );\n\n$args = array( 'post_type' => 'bio', 'posts_per_page' => 1 );\n// My second query for CPT 'bio'\n$bio_query = new WP_Query( $args );\n\n// The Loop\nif ( $bio_query->have_posts() ) {\n while ( $bio_query->have_posts() ) {\n $bio_query->the_post();\n // please, my custom post 'bio' !...\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n} else {\n // no posts found\n}\n?>\n</code></pre>\n\n<p>Also in <code>while ( $the_query->have_posts() )</code> you got a error on <code>$the_query</code>. It would be <code>$bio_query</code>. I've fixed the error in my above code.</p>\n\n<p>Hope it helps.</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252054",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110465/"
] |
*(Queries are definitively an infinite source of misunderstanding...)*
I try to display two types of informations in a tax archive (`taxonomy-artiste.php`) :
1. The content of a page from a custom post (bio)
2. And after, a list of post from another custom post (works)
If I understood well, it could be interesting to use pre\_get\_post to change the main query.
So, I set that in my `function.php`.
```
//Include all my CPT but the bio
function lm_exclude_bio( $query ) {
if( is_tax('artiste') && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'cpt#1', 'cpt#2'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'lm_exclude_bio' );
```
Ok, it works.
But, when I add a new query in this archive, it doesn't display the post I excepted...
```
$args = array( 'post_type' => 'bio', 'posts_per_page' => 1 );
// My second query for CPT 'bio'
$bio_query = new WP_Query( $args );
// The Loop
if ( $bio_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$bio_query->the_post();
// please, my custom post 'bio' !...
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
?>
```
Is it impossible( stupid ?) to set two queries with opposite arguments ?
Thanks for any help !
|
You've added the filter `lm_exclude_bio` to `pre_get_posts`. So when you need to run another query you can remove the filter to get normal query. You can remove the filter like below-
```
// Here we're removing the filter first. Then we are running the query.
remove_filter( 'pre_get_posts', 'lm_exclude_bio' );
$args = array( 'post_type' => 'bio', 'posts_per_page' => 1 );
// My second query for CPT 'bio'
$bio_query = new WP_Query( $args );
// The Loop
if ( $bio_query->have_posts() ) {
while ( $bio_query->have_posts() ) {
$bio_query->the_post();
// please, my custom post 'bio' !...
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
?>
```
Also in `while ( $the_query->have_posts() )` you got a error on `$the_query`. It would be `$bio_query`. I've fixed the error in my above code.
Hope it helps.
|
252,071 |
<p>I am attempting to import a site using XML generated by WordPress.com</p>
<p>All the posts and media seem to import, but the comments fail with errors</p>
<pre><code>Failed to import “Sarah Toon - 2015-10-10 08:29:30”: Invalid post type feedback
Failed to import “Kylie - 2015-10-10 08:34:50”: Invalid post type feedback
Failed to import “Sophie Ward - 2015-10-10 08:36:22”: Invalid post type feedback
</code></pre>
<p>Reading other posts, here on WordPress.SE none of them have an accepted answer. The closest I could find is <a href="https://wordpress.stackexchange.com/questions/49531/custom-post-types-not-imported-properly">Custom post types not imported properly</a> but that is about posts, not comments.</p>
<p>Can someone get me started on solving this please?</p>
|
[
{
"answer_id": 252078,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>The issue is you're trying to import posts with a post type of <code>feedback</code>, but there is no such post type registered on your install of WordPress.</p>\n\n<p>Quick-and-easy fix is to register one:</p>\n\n<pre><code>add_action( 'init', function () {\n register_post_type( 'feedback', [\n 'public' => true,\n 'labels' => [\n 'singular_name' => 'Feedback',\n 'name' => 'Feedback',\n ]\n ]);\n});\n</code></pre>\n\n<p>Place it in your theme's <code>functions.php</code>, or in a MU plugin (eg. <code>wp-content/mu-plugins/feedback.php</code>).</p>\n"
},
{
"answer_id": 278257,
"author": "Artistan",
"author_id": 126670,
"author_profile": "https://wordpress.stackexchange.com/users/126670",
"pm_score": 2,
"selected": false,
"text": "<p>The Jetpack plugin creates a custom post type of feedback when active.\nYou may need to just install that plugin first (as I did).\nCheers!</p>\n"
},
{
"answer_id": 363769,
"author": "Andres",
"author_id": 185857,
"author_profile": "https://wordpress.stackexchange.com/users/185857",
"pm_score": 0,
"selected": false,
"text": "<p>I was migrating a website from wordpress.com and I had same problem.</p>\n\n<p>I've solved first installing the Jetpack plugin, then activating the Contact Form module in this url <strong>[yoursite.com]/wp-admin/admin.php?page=jetpack_modules</strong> and finally doing the import.</p>\n\n<p>Hope that helps to someone!</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252071",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25717/"
] |
I am attempting to import a site using XML generated by WordPress.com
All the posts and media seem to import, but the comments fail with errors
```
Failed to import “Sarah Toon - 2015-10-10 08:29:30”: Invalid post type feedback
Failed to import “Kylie - 2015-10-10 08:34:50”: Invalid post type feedback
Failed to import “Sophie Ward - 2015-10-10 08:36:22”: Invalid post type feedback
```
Reading other posts, here on WordPress.SE none of them have an accepted answer. The closest I could find is [Custom post types not imported properly](https://wordpress.stackexchange.com/questions/49531/custom-post-types-not-imported-properly) but that is about posts, not comments.
Can someone get me started on solving this please?
|
The issue is you're trying to import posts with a post type of `feedback`, but there is no such post type registered on your install of WordPress.
Quick-and-easy fix is to register one:
```
add_action( 'init', function () {
register_post_type( 'feedback', [
'public' => true,
'labels' => [
'singular_name' => 'Feedback',
'name' => 'Feedback',
]
]);
});
```
Place it in your theme's `functions.php`, or in a MU plugin (eg. `wp-content/mu-plugins/feedback.php`).
|
252,073 |
<p>Hi Guys i found this code snippet on here: </p>
<pre><code>add_action( 'set_user_role', function( $user_id, $role, $old_roles )
{
// Your code ...
}, 10, 3 );
</code></pre>
<p>Source: <a href="https://wordpress.stackexchange.com/questions/194324/execute-a-function-when-admin-changes-the-user-role">Execute a function when admin changes the user role</a></p>
<p>And wanted to modify it it so that it could set the user roles in the following way: </p>
<p>1 user has roles "level0" and "customer" -> roles "level1" and "vendor"</p>
<p>2 user has roles "level1" and "vendor" -> roles "level0" and "customer"</p>
<p>In case the admin is changing the role "level0" to "level1" the code should update the second role from "customer" to "vendor" and vice versa.</p>
<p>i tried the following code but it is not working:</p>
<pre><code>add_action( 'set_user_role', 'rb_update_user_role',10,3);
function rb_update_user_role(){
$user_id = get_current_user_id();
$user = new WP_User ($user_id);
if (current_user_is('s2member_level0') && current_user_is('vendor')){
$user->remove_role('vendor');
$user->add_role('customer');
}
if(current_user_is('s2member_level1') && current_user_is ('customer')){
$user->remove_role('customer');
$user->add_role('vendor');
}
}
</code></pre>
<p>Has anyone suggestions or code snippets that could help me figure this out? Or do i need another approch on this?</p>
<p>EDIT: </p>
<p>I add the second role like this when the user is activated </p>
<pre><code>add_action( 'bp_core_activated_user', 'add_secondary_role_new', 10, 1 );
function add_secondary_role_new( $user_id ) {
global $members_template;
$user = get_user_by('id', $user_id);
if (user_can($members_template->member->id,'s2member_level1')){
$user->add_role('vendor');
}
else{
$user->add_role('customer');
}
</code></pre>
<p>}</p>
|
[
{
"answer_id": 252078,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>The issue is you're trying to import posts with a post type of <code>feedback</code>, but there is no such post type registered on your install of WordPress.</p>\n\n<p>Quick-and-easy fix is to register one:</p>\n\n<pre><code>add_action( 'init', function () {\n register_post_type( 'feedback', [\n 'public' => true,\n 'labels' => [\n 'singular_name' => 'Feedback',\n 'name' => 'Feedback',\n ]\n ]);\n});\n</code></pre>\n\n<p>Place it in your theme's <code>functions.php</code>, or in a MU plugin (eg. <code>wp-content/mu-plugins/feedback.php</code>).</p>\n"
},
{
"answer_id": 278257,
"author": "Artistan",
"author_id": 126670,
"author_profile": "https://wordpress.stackexchange.com/users/126670",
"pm_score": 2,
"selected": false,
"text": "<p>The Jetpack plugin creates a custom post type of feedback when active.\nYou may need to just install that plugin first (as I did).\nCheers!</p>\n"
},
{
"answer_id": 363769,
"author": "Andres",
"author_id": 185857,
"author_profile": "https://wordpress.stackexchange.com/users/185857",
"pm_score": 0,
"selected": false,
"text": "<p>I was migrating a website from wordpress.com and I had same problem.</p>\n\n<p>I've solved first installing the Jetpack plugin, then activating the Contact Form module in this url <strong>[yoursite.com]/wp-admin/admin.php?page=jetpack_modules</strong> and finally doing the import.</p>\n\n<p>Hope that helps to someone!</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252073",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102810/"
] |
Hi Guys i found this code snippet on here:
```
add_action( 'set_user_role', function( $user_id, $role, $old_roles )
{
// Your code ...
}, 10, 3 );
```
Source: [Execute a function when admin changes the user role](https://wordpress.stackexchange.com/questions/194324/execute-a-function-when-admin-changes-the-user-role)
And wanted to modify it it so that it could set the user roles in the following way:
1 user has roles "level0" and "customer" -> roles "level1" and "vendor"
2 user has roles "level1" and "vendor" -> roles "level0" and "customer"
In case the admin is changing the role "level0" to "level1" the code should update the second role from "customer" to "vendor" and vice versa.
i tried the following code but it is not working:
```
add_action( 'set_user_role', 'rb_update_user_role',10,3);
function rb_update_user_role(){
$user_id = get_current_user_id();
$user = new WP_User ($user_id);
if (current_user_is('s2member_level0') && current_user_is('vendor')){
$user->remove_role('vendor');
$user->add_role('customer');
}
if(current_user_is('s2member_level1') && current_user_is ('customer')){
$user->remove_role('customer');
$user->add_role('vendor');
}
}
```
Has anyone suggestions or code snippets that could help me figure this out? Or do i need another approch on this?
EDIT:
I add the second role like this when the user is activated
```
add_action( 'bp_core_activated_user', 'add_secondary_role_new', 10, 1 );
function add_secondary_role_new( $user_id ) {
global $members_template;
$user = get_user_by('id', $user_id);
if (user_can($members_template->member->id,'s2member_level1')){
$user->add_role('vendor');
}
else{
$user->add_role('customer');
}
```
}
|
The issue is you're trying to import posts with a post type of `feedback`, but there is no such post type registered on your install of WordPress.
Quick-and-easy fix is to register one:
```
add_action( 'init', function () {
register_post_type( 'feedback', [
'public' => true,
'labels' => [
'singular_name' => 'Feedback',
'name' => 'Feedback',
]
]);
});
```
Place it in your theme's `functions.php`, or in a MU plugin (eg. `wp-content/mu-plugins/feedback.php`).
|
252,079 |
<p>I am using a Genesis theme (digital-pro), and inside of the front-page.php file (companion to functions.php) I am noticing that js files are enqueued in two different ways.</p>
<p>Example 1: </p>
<pre><code>wp_enqueue_script( 'localScroll', get_stylesheet_directory_uri() . '/js/jquery.localScroll.min.js', array( 'scrollTo' ), '1.2.8b', true );
</code></pre>
<p>Example 2: </p>
<pre><code>wp_enqueue_script( 'digital-backstretch-set', get_bloginfo('stylesheet_directory').'/js/backstretch-set.js' , array( 'jquery', 'digital-backstretch' ), '1.0.0' );
</code></pre>
<p>In the first example, <code>get_stylesheet_directory_uri()</code> is used before concatenating the js file path, and in the second example <code>get_bloginfo('stylesheet_directory')</code> is used instead. </p>
<p>Does anyone have any insight into why this might be? Is it better to use one method over the other? Or in different circumstances?</p>
<p>Thanks! </p>
|
[
{
"answer_id": 252083,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>Starting from WordPress 4.7, I would use <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_theme_file_uri()</code></a>, so any child theme can override the file easily: if the file exists in the child theme, <code>get_theme_file_uri()</code> returns the URI to that file, otherwise returns the file in the parent theme:</p>\n\n<pre><code>wp_enqueue_script( 'localScroll', get_theme_file_uri( 'js/jquery.localScroll.min.js' ), array( 'scrollTo' ), '1.2.8b', true );\n</code></pre>\n\n<p>If you want to <em>hard</em> link to a file in the parent theme not allowing it to be overriden by a child theme, use <a href=\"https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_parent_theme_file()</code></a>.</p>\n\n<p>But responding specifically to your question, both methods do the same; in fact, <code>get_bloginfo( 'stylesheet_directory' )</code> is a wrapper for <code>get_stylesheet_directory_uri()</code> as you can see in the <a href=\"https://developer.wordpress.org/reference/functions/get_bloginfo/#source\" rel=\"nofollow noreferrer\">source code</a>:</p>\n\n<pre><code>case 'stylesheet_directory':\n $output = get_stylesheet_directory_uri();\n break;\n</code></pre>\n\n<p>But I would avoid <code>get_bloginfo()</code> if a specific getter function exists; it may be more consistent in long way.</p>\n\n<p><code>get_stylesheet_directory_uri()</code> and <code>get_template_directory_uri()</code> still exists, are valid and can be used but those functions should be used only when you need specifically the URI of the shtylesheet/template <strong>directory</strong>, not a URI to a <strong>file</strong>.</p>\n\n<p>For example, imaging we have a file located in <code>assets/js/script.js</code> whithin the theme folder; then we can use all of this options:</p>\n\n<ol>\n<li><code>get_styleseet_directory_uri() . '/assets/js/script.js';</code></li>\n<li><code>get_template_directory_uri() . '/assets/js/script.js';</code></li>\n<li><code>get_theme_file_uri( 'assets/js/script.js' );</code></li>\n</ol>\n\n<p>In a theme with no childs, all three options will output the <strong>same URI</strong>; but if you develop a child theme:</p>\n\n<ol>\n<li>The option 1 will link to a file in the child theme directory whitout checking if it exists. In this case, we are required to copy the file to the child theme, even if we don't need to modify it.</li>\n<li>The option 2 will link to a file in the parent theme; no options to override it (well, it can be done using some filter hooks, but not in a direct way).</li>\n<li>With the option 3 you can leave the file in the parent theme if you are not going to modify it; or you can move the file to the child theme if you need to override it. No extra code is needed. As easy as it is sound.</li>\n</ol>\n\n<p>Internally, <code>get_theme_file_uri()</code>first checks if the file exists in the stylesheet directory, if it exists it returns <code>get_styleseet_directory_uri() . $file;</code>. If the file doesn't exist in the child theme, then it returns <code>get_template_directory_uri() . $file;</code>. It is like one level up over the other functions.</p>\n\n<p>Along with <code>get_theme_file_uri()</code>, <code>get_theme_file_path()</code> was introduced to get the path to the file instead of the URI; <code>get_parent_theme_file_uri()</code> and <code>get_parent_theme_file_path()</code> are also available but they will always use the parent file files, no matter if a child theme is active.</p>\n"
},
{
"answer_id": 252203,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>The new quatro:</p>\n\n<pre><code>get_theme_file_uri()\nget_parent_theme_file_uri()\nget_theme_file_path()\nget_parent_theme_file_path()\n</code></pre>\n\n<p>came to replace the old quatro:</p>\n\n<pre><code>get_stylesheet_directory_uri()\nget_template_directory_uri()\nget_stylesheet_directory()\nget_template_directory()\n</code></pre>\n\n<p>In the respective order.\nThe gain I would like to outline is the naming convention — much better now when you create themes.</p>\n\n<p>There is one problem. \nStill, there are many WordPress installations that use WP lower than 4.7.\nIf you know you run WordPress 4.7 or greater you are good.</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252079",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110604/"
] |
I am using a Genesis theme (digital-pro), and inside of the front-page.php file (companion to functions.php) I am noticing that js files are enqueued in two different ways.
Example 1:
```
wp_enqueue_script( 'localScroll', get_stylesheet_directory_uri() . '/js/jquery.localScroll.min.js', array( 'scrollTo' ), '1.2.8b', true );
```
Example 2:
```
wp_enqueue_script( 'digital-backstretch-set', get_bloginfo('stylesheet_directory').'/js/backstretch-set.js' , array( 'jquery', 'digital-backstretch' ), '1.0.0' );
```
In the first example, `get_stylesheet_directory_uri()` is used before concatenating the js file path, and in the second example `get_bloginfo('stylesheet_directory')` is used instead.
Does anyone have any insight into why this might be? Is it better to use one method over the other? Or in different circumstances?
Thanks!
|
Starting from WordPress 4.7, I would use [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/), so any child theme can override the file easily: if the file exists in the child theme, `get_theme_file_uri()` returns the URI to that file, otherwise returns the file in the parent theme:
```
wp_enqueue_script( 'localScroll', get_theme_file_uri( 'js/jquery.localScroll.min.js' ), array( 'scrollTo' ), '1.2.8b', true );
```
If you want to *hard* link to a file in the parent theme not allowing it to be overriden by a child theme, use [`get_parent_theme_file()`](https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/).
But responding specifically to your question, both methods do the same; in fact, `get_bloginfo( 'stylesheet_directory' )` is a wrapper for `get_stylesheet_directory_uri()` as you can see in the [source code](https://developer.wordpress.org/reference/functions/get_bloginfo/#source):
```
case 'stylesheet_directory':
$output = get_stylesheet_directory_uri();
break;
```
But I would avoid `get_bloginfo()` if a specific getter function exists; it may be more consistent in long way.
`get_stylesheet_directory_uri()` and `get_template_directory_uri()` still exists, are valid and can be used but those functions should be used only when you need specifically the URI of the shtylesheet/template **directory**, not a URI to a **file**.
For example, imaging we have a file located in `assets/js/script.js` whithin the theme folder; then we can use all of this options:
1. `get_styleseet_directory_uri() . '/assets/js/script.js';`
2. `get_template_directory_uri() . '/assets/js/script.js';`
3. `get_theme_file_uri( 'assets/js/script.js' );`
In a theme with no childs, all three options will output the **same URI**; but if you develop a child theme:
1. The option 1 will link to a file in the child theme directory whitout checking if it exists. In this case, we are required to copy the file to the child theme, even if we don't need to modify it.
2. The option 2 will link to a file in the parent theme; no options to override it (well, it can be done using some filter hooks, but not in a direct way).
3. With the option 3 you can leave the file in the parent theme if you are not going to modify it; or you can move the file to the child theme if you need to override it. No extra code is needed. As easy as it is sound.
Internally, `get_theme_file_uri()`first checks if the file exists in the stylesheet directory, if it exists it returns `get_styleseet_directory_uri() . $file;`. If the file doesn't exist in the child theme, then it returns `get_template_directory_uri() . $file;`. It is like one level up over the other functions.
Along with `get_theme_file_uri()`, `get_theme_file_path()` was introduced to get the path to the file instead of the URI; `get_parent_theme_file_uri()` and `get_parent_theme_file_path()` are also available but they will always use the parent file files, no matter if a child theme is active.
|
252,085 |
<p>Hi I am using thevoux theme for my website as i need to add pagination links like "Older Posts and Newer Posts" to home page.Here is an example screen shot how it should be.
<a href="https://i.stack.imgur.com/4rWAj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4rWAj.jpg" alt="enter image description here"></a></p>
<p>Actually right now i am getting these links in menus in the same way i need to display them in home page as well.</p>
<pre><code><?php get_header(); ?>
<?php
$blog_featured = ot_get_option('blog_featured');
?>
<?php if ($blog_featured) { ?>
<div class="row header_content">
<div class="small-12 columns">
<?php
$args = array(
'p' => $blog_featured,
'post_type' => 'any'
);
$featured_post = new WP_Query($args);
?>
<?php if ($featured_post->have_posts()) : while ($featured_post->have_posts()) : $featured_post->the_post(); ?>
<?php get_template_part( 'inc/loop/blog-featured' ); ?>
<?php endwhile; else : endif; ?>
</div>
</div>
<?php } ?>
<div class="row">
<section class="blog-section small-12 medium-8 columns">
<div class="row" data-equal=">.columns">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part( 'inc/loop/blog-list' ); ?>
<?php endwhile; else : ?>
<?php get_template_part( 'inc/loop/notfound' ); ?>
<?php endif; ?>
</div>
<?php if ( get_next_posts_link() || get_previous_posts_link()) { ?>
<div class="blog_nav">
<?php if ( get_next_posts_link() ) : ?>
<a href="<?php echo next_posts(); ?>" class="next"><i class="fa fa-angle-left"></i> <?php _e( 'Older Posts', 'thevoux' ); ?></a>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<a href="<?php echo previous_posts(); ?>" class="prev"><?php _e( 'Newer Posts', 'thevoux' ); ?> <i class="fa fa-angle-right"></i></a>
<?php endif; ?>
</div>
<?php } ?>
</section>
<?php get_sidebar(); ?>
</div>
</code></pre>
|
[
{
"answer_id": 252083,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>Starting from WordPress 4.7, I would use <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_theme_file_uri()</code></a>, so any child theme can override the file easily: if the file exists in the child theme, <code>get_theme_file_uri()</code> returns the URI to that file, otherwise returns the file in the parent theme:</p>\n\n<pre><code>wp_enqueue_script( 'localScroll', get_theme_file_uri( 'js/jquery.localScroll.min.js' ), array( 'scrollTo' ), '1.2.8b', true );\n</code></pre>\n\n<p>If you want to <em>hard</em> link to a file in the parent theme not allowing it to be overriden by a child theme, use <a href=\"https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_parent_theme_file()</code></a>.</p>\n\n<p>But responding specifically to your question, both methods do the same; in fact, <code>get_bloginfo( 'stylesheet_directory' )</code> is a wrapper for <code>get_stylesheet_directory_uri()</code> as you can see in the <a href=\"https://developer.wordpress.org/reference/functions/get_bloginfo/#source\" rel=\"nofollow noreferrer\">source code</a>:</p>\n\n<pre><code>case 'stylesheet_directory':\n $output = get_stylesheet_directory_uri();\n break;\n</code></pre>\n\n<p>But I would avoid <code>get_bloginfo()</code> if a specific getter function exists; it may be more consistent in long way.</p>\n\n<p><code>get_stylesheet_directory_uri()</code> and <code>get_template_directory_uri()</code> still exists, are valid and can be used but those functions should be used only when you need specifically the URI of the shtylesheet/template <strong>directory</strong>, not a URI to a <strong>file</strong>.</p>\n\n<p>For example, imaging we have a file located in <code>assets/js/script.js</code> whithin the theme folder; then we can use all of this options:</p>\n\n<ol>\n<li><code>get_styleseet_directory_uri() . '/assets/js/script.js';</code></li>\n<li><code>get_template_directory_uri() . '/assets/js/script.js';</code></li>\n<li><code>get_theme_file_uri( 'assets/js/script.js' );</code></li>\n</ol>\n\n<p>In a theme with no childs, all three options will output the <strong>same URI</strong>; but if you develop a child theme:</p>\n\n<ol>\n<li>The option 1 will link to a file in the child theme directory whitout checking if it exists. In this case, we are required to copy the file to the child theme, even if we don't need to modify it.</li>\n<li>The option 2 will link to a file in the parent theme; no options to override it (well, it can be done using some filter hooks, but not in a direct way).</li>\n<li>With the option 3 you can leave the file in the parent theme if you are not going to modify it; or you can move the file to the child theme if you need to override it. No extra code is needed. As easy as it is sound.</li>\n</ol>\n\n<p>Internally, <code>get_theme_file_uri()</code>first checks if the file exists in the stylesheet directory, if it exists it returns <code>get_styleseet_directory_uri() . $file;</code>. If the file doesn't exist in the child theme, then it returns <code>get_template_directory_uri() . $file;</code>. It is like one level up over the other functions.</p>\n\n<p>Along with <code>get_theme_file_uri()</code>, <code>get_theme_file_path()</code> was introduced to get the path to the file instead of the URI; <code>get_parent_theme_file_uri()</code> and <code>get_parent_theme_file_path()</code> are also available but they will always use the parent file files, no matter if a child theme is active.</p>\n"
},
{
"answer_id": 252203,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>The new quatro:</p>\n\n<pre><code>get_theme_file_uri()\nget_parent_theme_file_uri()\nget_theme_file_path()\nget_parent_theme_file_path()\n</code></pre>\n\n<p>came to replace the old quatro:</p>\n\n<pre><code>get_stylesheet_directory_uri()\nget_template_directory_uri()\nget_stylesheet_directory()\nget_template_directory()\n</code></pre>\n\n<p>In the respective order.\nThe gain I would like to outline is the naming convention — much better now when you create themes.</p>\n\n<p>There is one problem. \nStill, there are many WordPress installations that use WP lower than 4.7.\nIf you know you run WordPress 4.7 or greater you are good.</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252085",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110685/"
] |
Hi I am using thevoux theme for my website as i need to add pagination links like "Older Posts and Newer Posts" to home page.Here is an example screen shot how it should be.
[](https://i.stack.imgur.com/4rWAj.jpg)
Actually right now i am getting these links in menus in the same way i need to display them in home page as well.
```
<?php get_header(); ?>
<?php
$blog_featured = ot_get_option('blog_featured');
?>
<?php if ($blog_featured) { ?>
<div class="row header_content">
<div class="small-12 columns">
<?php
$args = array(
'p' => $blog_featured,
'post_type' => 'any'
);
$featured_post = new WP_Query($args);
?>
<?php if ($featured_post->have_posts()) : while ($featured_post->have_posts()) : $featured_post->the_post(); ?>
<?php get_template_part( 'inc/loop/blog-featured' ); ?>
<?php endwhile; else : endif; ?>
</div>
</div>
<?php } ?>
<div class="row">
<section class="blog-section small-12 medium-8 columns">
<div class="row" data-equal=">.columns">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part( 'inc/loop/blog-list' ); ?>
<?php endwhile; else : ?>
<?php get_template_part( 'inc/loop/notfound' ); ?>
<?php endif; ?>
</div>
<?php if ( get_next_posts_link() || get_previous_posts_link()) { ?>
<div class="blog_nav">
<?php if ( get_next_posts_link() ) : ?>
<a href="<?php echo next_posts(); ?>" class="next"><i class="fa fa-angle-left"></i> <?php _e( 'Older Posts', 'thevoux' ); ?></a>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<a href="<?php echo previous_posts(); ?>" class="prev"><?php _e( 'Newer Posts', 'thevoux' ); ?> <i class="fa fa-angle-right"></i></a>
<?php endif; ?>
</div>
<?php } ?>
</section>
<?php get_sidebar(); ?>
</div>
```
|
Starting from WordPress 4.7, I would use [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/), so any child theme can override the file easily: if the file exists in the child theme, `get_theme_file_uri()` returns the URI to that file, otherwise returns the file in the parent theme:
```
wp_enqueue_script( 'localScroll', get_theme_file_uri( 'js/jquery.localScroll.min.js' ), array( 'scrollTo' ), '1.2.8b', true );
```
If you want to *hard* link to a file in the parent theme not allowing it to be overriden by a child theme, use [`get_parent_theme_file()`](https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/).
But responding specifically to your question, both methods do the same; in fact, `get_bloginfo( 'stylesheet_directory' )` is a wrapper for `get_stylesheet_directory_uri()` as you can see in the [source code](https://developer.wordpress.org/reference/functions/get_bloginfo/#source):
```
case 'stylesheet_directory':
$output = get_stylesheet_directory_uri();
break;
```
But I would avoid `get_bloginfo()` if a specific getter function exists; it may be more consistent in long way.
`get_stylesheet_directory_uri()` and `get_template_directory_uri()` still exists, are valid and can be used but those functions should be used only when you need specifically the URI of the shtylesheet/template **directory**, not a URI to a **file**.
For example, imaging we have a file located in `assets/js/script.js` whithin the theme folder; then we can use all of this options:
1. `get_styleseet_directory_uri() . '/assets/js/script.js';`
2. `get_template_directory_uri() . '/assets/js/script.js';`
3. `get_theme_file_uri( 'assets/js/script.js' );`
In a theme with no childs, all three options will output the **same URI**; but if you develop a child theme:
1. The option 1 will link to a file in the child theme directory whitout checking if it exists. In this case, we are required to copy the file to the child theme, even if we don't need to modify it.
2. The option 2 will link to a file in the parent theme; no options to override it (well, it can be done using some filter hooks, but not in a direct way).
3. With the option 3 you can leave the file in the parent theme if you are not going to modify it; or you can move the file to the child theme if you need to override it. No extra code is needed. As easy as it is sound.
Internally, `get_theme_file_uri()`first checks if the file exists in the stylesheet directory, if it exists it returns `get_styleseet_directory_uri() . $file;`. If the file doesn't exist in the child theme, then it returns `get_template_directory_uri() . $file;`. It is like one level up over the other functions.
Along with `get_theme_file_uri()`, `get_theme_file_path()` was introduced to get the path to the file instead of the URI; `get_parent_theme_file_uri()` and `get_parent_theme_file_path()` are also available but they will always use the parent file files, no matter if a child theme is active.
|
252,121 |
<p>I want to resize images in uploads folder. What would be the best way to resize images on a live website?</p>
|
[
{
"answer_id": 252083,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>Starting from WordPress 4.7, I would use <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_theme_file_uri()</code></a>, so any child theme can override the file easily: if the file exists in the child theme, <code>get_theme_file_uri()</code> returns the URI to that file, otherwise returns the file in the parent theme:</p>\n\n<pre><code>wp_enqueue_script( 'localScroll', get_theme_file_uri( 'js/jquery.localScroll.min.js' ), array( 'scrollTo' ), '1.2.8b', true );\n</code></pre>\n\n<p>If you want to <em>hard</em> link to a file in the parent theme not allowing it to be overriden by a child theme, use <a href=\"https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_parent_theme_file()</code></a>.</p>\n\n<p>But responding specifically to your question, both methods do the same; in fact, <code>get_bloginfo( 'stylesheet_directory' )</code> is a wrapper for <code>get_stylesheet_directory_uri()</code> as you can see in the <a href=\"https://developer.wordpress.org/reference/functions/get_bloginfo/#source\" rel=\"nofollow noreferrer\">source code</a>:</p>\n\n<pre><code>case 'stylesheet_directory':\n $output = get_stylesheet_directory_uri();\n break;\n</code></pre>\n\n<p>But I would avoid <code>get_bloginfo()</code> if a specific getter function exists; it may be more consistent in long way.</p>\n\n<p><code>get_stylesheet_directory_uri()</code> and <code>get_template_directory_uri()</code> still exists, are valid and can be used but those functions should be used only when you need specifically the URI of the shtylesheet/template <strong>directory</strong>, not a URI to a <strong>file</strong>.</p>\n\n<p>For example, imaging we have a file located in <code>assets/js/script.js</code> whithin the theme folder; then we can use all of this options:</p>\n\n<ol>\n<li><code>get_styleseet_directory_uri() . '/assets/js/script.js';</code></li>\n<li><code>get_template_directory_uri() . '/assets/js/script.js';</code></li>\n<li><code>get_theme_file_uri( 'assets/js/script.js' );</code></li>\n</ol>\n\n<p>In a theme with no childs, all three options will output the <strong>same URI</strong>; but if you develop a child theme:</p>\n\n<ol>\n<li>The option 1 will link to a file in the child theme directory whitout checking if it exists. In this case, we are required to copy the file to the child theme, even if we don't need to modify it.</li>\n<li>The option 2 will link to a file in the parent theme; no options to override it (well, it can be done using some filter hooks, but not in a direct way).</li>\n<li>With the option 3 you can leave the file in the parent theme if you are not going to modify it; or you can move the file to the child theme if you need to override it. No extra code is needed. As easy as it is sound.</li>\n</ol>\n\n<p>Internally, <code>get_theme_file_uri()</code>first checks if the file exists in the stylesheet directory, if it exists it returns <code>get_styleseet_directory_uri() . $file;</code>. If the file doesn't exist in the child theme, then it returns <code>get_template_directory_uri() . $file;</code>. It is like one level up over the other functions.</p>\n\n<p>Along with <code>get_theme_file_uri()</code>, <code>get_theme_file_path()</code> was introduced to get the path to the file instead of the URI; <code>get_parent_theme_file_uri()</code> and <code>get_parent_theme_file_path()</code> are also available but they will always use the parent file files, no matter if a child theme is active.</p>\n"
},
{
"answer_id": 252203,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>The new quatro:</p>\n\n<pre><code>get_theme_file_uri()\nget_parent_theme_file_uri()\nget_theme_file_path()\nget_parent_theme_file_path()\n</code></pre>\n\n<p>came to replace the old quatro:</p>\n\n<pre><code>get_stylesheet_directory_uri()\nget_template_directory_uri()\nget_stylesheet_directory()\nget_template_directory()\n</code></pre>\n\n<p>In the respective order.\nThe gain I would like to outline is the naming convention — much better now when you create themes.</p>\n\n<p>There is one problem. \nStill, there are many WordPress installations that use WP lower than 4.7.\nIf you know you run WordPress 4.7 or greater you are good.</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252121",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
I want to resize images in uploads folder. What would be the best way to resize images on a live website?
|
Starting from WordPress 4.7, I would use [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/), so any child theme can override the file easily: if the file exists in the child theme, `get_theme_file_uri()` returns the URI to that file, otherwise returns the file in the parent theme:
```
wp_enqueue_script( 'localScroll', get_theme_file_uri( 'js/jquery.localScroll.min.js' ), array( 'scrollTo' ), '1.2.8b', true );
```
If you want to *hard* link to a file in the parent theme not allowing it to be overriden by a child theme, use [`get_parent_theme_file()`](https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/).
But responding specifically to your question, both methods do the same; in fact, `get_bloginfo( 'stylesheet_directory' )` is a wrapper for `get_stylesheet_directory_uri()` as you can see in the [source code](https://developer.wordpress.org/reference/functions/get_bloginfo/#source):
```
case 'stylesheet_directory':
$output = get_stylesheet_directory_uri();
break;
```
But I would avoid `get_bloginfo()` if a specific getter function exists; it may be more consistent in long way.
`get_stylesheet_directory_uri()` and `get_template_directory_uri()` still exists, are valid and can be used but those functions should be used only when you need specifically the URI of the shtylesheet/template **directory**, not a URI to a **file**.
For example, imaging we have a file located in `assets/js/script.js` whithin the theme folder; then we can use all of this options:
1. `get_styleseet_directory_uri() . '/assets/js/script.js';`
2. `get_template_directory_uri() . '/assets/js/script.js';`
3. `get_theme_file_uri( 'assets/js/script.js' );`
In a theme with no childs, all three options will output the **same URI**; but if you develop a child theme:
1. The option 1 will link to a file in the child theme directory whitout checking if it exists. In this case, we are required to copy the file to the child theme, even if we don't need to modify it.
2. The option 2 will link to a file in the parent theme; no options to override it (well, it can be done using some filter hooks, but not in a direct way).
3. With the option 3 you can leave the file in the parent theme if you are not going to modify it; or you can move the file to the child theme if you need to override it. No extra code is needed. As easy as it is sound.
Internally, `get_theme_file_uri()`first checks if the file exists in the stylesheet directory, if it exists it returns `get_styleseet_directory_uri() . $file;`. If the file doesn't exist in the child theme, then it returns `get_template_directory_uri() . $file;`. It is like one level up over the other functions.
Along with `get_theme_file_uri()`, `get_theme_file_path()` was introduced to get the path to the file instead of the URI; `get_parent_theme_file_uri()` and `get_parent_theme_file_path()` are also available but they will always use the parent file files, no matter if a child theme is active.
|
252,133 |
<p>I am having trouble finding a good resource on using the $wpdb function.</p>
<p>I am trying to delete a row from a custom table named: eLearning_progress</p>
<pre><code>$removefromdb = $wpdb->query("DELETE FROM eLearning_progress WHERE ID = '$user_id' AND module_id = '$singlecomparearrays_remove'" );
</code></pre>
<p>The row I would like to delete has the ID of '$user_id' and the 'module_id' of '$singlecomparearrays_remove'.</p>
<p>I have also tried: </p>
<pre><code>$removefromdb = $wpdb->query( "DELETE FROM eLearning_progress WHERE ID = ($user_id) AND module_id = ($singlecomparearrays_remove)" );
</code></pre>
<p>and then:</p>
<pre><code>$removefromdb = $wpdb->query($wpdb->prepare("DELETE FROM eLearning_progress WHERE ID = %s AND module_id = %s", $user_id, $singlecomparearrays_remove));
</code></pre>
<p>Please try not to sigh too loudly at my attempts but I can't find a good guide on using the DELETE command with variables in there too.
Any help is much appreciated.</p>
<p>Regards,
Alex</p>
|
[
{
"answer_id": 252222,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 6,
"selected": true,
"text": "<p>The best WP API solution for this goal is to use the <a href=\"https://developer.wordpress.org/reference/classes/wpdb/delete/\" rel=\"nofollow noreferrer\"><code>delete()</code></a> function to remove a row.</p>\n<p>A small example, to delete the raw <code>ID</code> in the custom table <code>eLearning_progress</code>.</p>\n<pre class=\"lang-php prettyprint-override\"><code> $id = 0815;\n $table = 'eLearning_progress';\n $wpdb->delete( $table, array( 'id' => $id ) );\n</code></pre>\n<p>But I can't see which raw you will delete in your table <code>eLearning_progress</code>? Maybe you enhance the question to understand it much better.</p>\n"
},
{
"answer_id": 329956,
"author": "Adi Prasetyo",
"author_id": 89333,
"author_profile": "https://wordpress.stackexchange.com/users/89333",
"pm_score": 0,
"selected": false,
"text": "<p>It still possible that your sql is creating trouble even use <code>$wpdb->delete</code>\nI found it useful using one of these approach:</p>\n\n<ol>\n<li>call <code>$wpdb->show_errors();</code> <a href=\"https://wordpress.stackexchange.com/a/225176/89333\">before</a> querying</li>\n<li><a href=\"https://www.wpoptimus.com/1832/debug-wpdb-database-queries/\" rel=\"nofollow noreferrer\">enable</a> debug mode with\n <code>define( 'WP_DEBUG', true );</code>\non your <strong>wp-config.php</strong></li>\n</ol>\n"
},
{
"answer_id": 400328,
"author": "user216942",
"author_id": 216942,
"author_profile": "https://wordpress.stackexchange.com/users/216942",
"pm_score": 0,
"selected": false,
"text": "<p>Using This You can easily delete</p>\n<pre><code>$MailMetaKey = yourkey\n$post_id = yourpostid\n\n$wpdb->query($wpdb->prepare("DELETE * FROM f0_postmeta WHERE meta_key = $MailMetaKey' and post_id = '$post_id' "));\n</code></pre>\n"
},
{
"answer_id": 400929,
"author": "Qureshi Taha",
"author_id": 217545,
"author_profile": "https://wordpress.stackexchange.com/users/217545",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$wpdb->query($wpdb->prepare("DELETE FROM f0_postmeta WHERE meta_key = '_lottery_closed' and post_id = '$prdid'"));\n</code></pre>\n<p>This is working fine for me</p>\n"
},
{
"answer_id": 404835,
"author": "Samidul Islam",
"author_id": 192435,
"author_profile": "https://wordpress.stackexchange.com/users/192435",
"pm_score": 0,
"selected": false,
"text": "<p><strong>This code not working, show an error. I'm tried</strong></p>\n<p>Please look at this screenshot <a href=\"https://prnt.sc/M3DYH_EmHCtM\" rel=\"nofollow noreferrer\">https://prnt.sc/M3DYH_EmHCtM</a></p>\n<pre><code>global $wpdb;\n\n$id = $_REQUEST['delete'];\n\n$table = 'custom_user_info';\n\n$wpdb->delete( $table, array( 'id' => $id ) );\n</code></pre>\n<p><strong>But when I'm using this code, It's working perfectly</strong></p>\n<pre><code>$db_config = mysqli_connect('localhost', 'root', '', 'develop');\n\n$id = $_REQUEST['delete'];\n\n$delete = "DELETE FROM custom_user_info WHERE id=$id";\n\n$query = mysqli_query($db_config, $delete);\n</code></pre>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252133",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110723/"
] |
I am having trouble finding a good resource on using the $wpdb function.
I am trying to delete a row from a custom table named: eLearning\_progress
```
$removefromdb = $wpdb->query("DELETE FROM eLearning_progress WHERE ID = '$user_id' AND module_id = '$singlecomparearrays_remove'" );
```
The row I would like to delete has the ID of '$user\_id' and the 'module\_id' of '$singlecomparearrays\_remove'.
I have also tried:
```
$removefromdb = $wpdb->query( "DELETE FROM eLearning_progress WHERE ID = ($user_id) AND module_id = ($singlecomparearrays_remove)" );
```
and then:
```
$removefromdb = $wpdb->query($wpdb->prepare("DELETE FROM eLearning_progress WHERE ID = %s AND module_id = %s", $user_id, $singlecomparearrays_remove));
```
Please try not to sigh too loudly at my attempts but I can't find a good guide on using the DELETE command with variables in there too.
Any help is much appreciated.
Regards,
Alex
|
The best WP API solution for this goal is to use the [`delete()`](https://developer.wordpress.org/reference/classes/wpdb/delete/) function to remove a row.
A small example, to delete the raw `ID` in the custom table `eLearning_progress`.
```php
$id = 0815;
$table = 'eLearning_progress';
$wpdb->delete( $table, array( 'id' => $id ) );
```
But I can't see which raw you will delete in your table `eLearning_progress`? Maybe you enhance the question to understand it much better.
|
252,134 |
<p>I'm trying to get value of hidden <code>textarea</code> created by <code>wp_editor()</code> or check if anything is typed it, but the problem is that the value is updated on submit, not dynamically. What I need is to validate with jQuery whether the field is filled in or not.</p>
<p>My field:</p>
<pre><code>$settings = array(
'editor_height' => 300,
'media_buttons' => false,
'teeny' => false,
'quicktags' => false
);
wp_editor( $post->post_content ,'my_content', $settings);
</code></pre>
<p>The only idea that I get is:</p>
<pre><code>var name = $('iframe#st_content_ifr').contents().find('#tinymce p').length;
</code></pre>
<p>and then count paragraphs, but this solution seems to me a bit silly. Is there any better way?</p>
|
[
{
"answer_id": 252222,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 6,
"selected": true,
"text": "<p>The best WP API solution for this goal is to use the <a href=\"https://developer.wordpress.org/reference/classes/wpdb/delete/\" rel=\"nofollow noreferrer\"><code>delete()</code></a> function to remove a row.</p>\n<p>A small example, to delete the raw <code>ID</code> in the custom table <code>eLearning_progress</code>.</p>\n<pre class=\"lang-php prettyprint-override\"><code> $id = 0815;\n $table = 'eLearning_progress';\n $wpdb->delete( $table, array( 'id' => $id ) );\n</code></pre>\n<p>But I can't see which raw you will delete in your table <code>eLearning_progress</code>? Maybe you enhance the question to understand it much better.</p>\n"
},
{
"answer_id": 329956,
"author": "Adi Prasetyo",
"author_id": 89333,
"author_profile": "https://wordpress.stackexchange.com/users/89333",
"pm_score": 0,
"selected": false,
"text": "<p>It still possible that your sql is creating trouble even use <code>$wpdb->delete</code>\nI found it useful using one of these approach:</p>\n\n<ol>\n<li>call <code>$wpdb->show_errors();</code> <a href=\"https://wordpress.stackexchange.com/a/225176/89333\">before</a> querying</li>\n<li><a href=\"https://www.wpoptimus.com/1832/debug-wpdb-database-queries/\" rel=\"nofollow noreferrer\">enable</a> debug mode with\n <code>define( 'WP_DEBUG', true );</code>\non your <strong>wp-config.php</strong></li>\n</ol>\n"
},
{
"answer_id": 400328,
"author": "user216942",
"author_id": 216942,
"author_profile": "https://wordpress.stackexchange.com/users/216942",
"pm_score": 0,
"selected": false,
"text": "<p>Using This You can easily delete</p>\n<pre><code>$MailMetaKey = yourkey\n$post_id = yourpostid\n\n$wpdb->query($wpdb->prepare("DELETE * FROM f0_postmeta WHERE meta_key = $MailMetaKey' and post_id = '$post_id' "));\n</code></pre>\n"
},
{
"answer_id": 400929,
"author": "Qureshi Taha",
"author_id": 217545,
"author_profile": "https://wordpress.stackexchange.com/users/217545",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$wpdb->query($wpdb->prepare("DELETE FROM f0_postmeta WHERE meta_key = '_lottery_closed' and post_id = '$prdid'"));\n</code></pre>\n<p>This is working fine for me</p>\n"
},
{
"answer_id": 404835,
"author": "Samidul Islam",
"author_id": 192435,
"author_profile": "https://wordpress.stackexchange.com/users/192435",
"pm_score": 0,
"selected": false,
"text": "<p><strong>This code not working, show an error. I'm tried</strong></p>\n<p>Please look at this screenshot <a href=\"https://prnt.sc/M3DYH_EmHCtM\" rel=\"nofollow noreferrer\">https://prnt.sc/M3DYH_EmHCtM</a></p>\n<pre><code>global $wpdb;\n\n$id = $_REQUEST['delete'];\n\n$table = 'custom_user_info';\n\n$wpdb->delete( $table, array( 'id' => $id ) );\n</code></pre>\n<p><strong>But when I'm using this code, It's working perfectly</strong></p>\n<pre><code>$db_config = mysqli_connect('localhost', 'root', '', 'develop');\n\n$id = $_REQUEST['delete'];\n\n$delete = "DELETE FROM custom_user_info WHERE id=$id";\n\n$query = mysqli_query($db_config, $delete);\n</code></pre>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105189/"
] |
I'm trying to get value of hidden `textarea` created by `wp_editor()` or check if anything is typed it, but the problem is that the value is updated on submit, not dynamically. What I need is to validate with jQuery whether the field is filled in or not.
My field:
```
$settings = array(
'editor_height' => 300,
'media_buttons' => false,
'teeny' => false,
'quicktags' => false
);
wp_editor( $post->post_content ,'my_content', $settings);
```
The only idea that I get is:
```
var name = $('iframe#st_content_ifr').contents().find('#tinymce p').length;
```
and then count paragraphs, but this solution seems to me a bit silly. Is there any better way?
|
The best WP API solution for this goal is to use the [`delete()`](https://developer.wordpress.org/reference/classes/wpdb/delete/) function to remove a row.
A small example, to delete the raw `ID` in the custom table `eLearning_progress`.
```php
$id = 0815;
$table = 'eLearning_progress';
$wpdb->delete( $table, array( 'id' => $id ) );
```
But I can't see which raw you will delete in your table `eLearning_progress`? Maybe you enhance the question to understand it much better.
|
252,135 |
<p>After I moved Wordpress to a subfolder, I'm getting the following error at Chrome console:</p>
<pre><code>GET http://www.mydomain.comwp-includes/js/wp-embed.min.js?ver=4.5.4 net::ERR_NAME_NOT_RESOLVED
</code></pre>
<p>See? It's missing a "/" after the domain name.</p>
<p>What's the best approach to solve this? 301 redirects on htaccess seems very intrusive, is there any configuration I'm missing here?</p>
|
[
{
"answer_id": 252136,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 2,
"selected": false,
"text": "<p>I solved it by logging in into admin panel and saving site URL with a trailing slash at the end.</p>\n"
},
{
"answer_id": 381545,
"author": "Leon Ni",
"author_id": 200402,
"author_profile": "https://wordpress.stackexchange.com/users/200402",
"pm_score": 0,
"selected": false,
"text": "<p>add this line anywhere in the wp-config.php file:</p>\n<pre><code>define('WP_SITEURL', 'http://example.com/');\n</code></pre>\n<p>It solved the problem for me.</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27278/"
] |
After I moved Wordpress to a subfolder, I'm getting the following error at Chrome console:
```
GET http://www.mydomain.comwp-includes/js/wp-embed.min.js?ver=4.5.4 net::ERR_NAME_NOT_RESOLVED
```
See? It's missing a "/" after the domain name.
What's the best approach to solve this? 301 redirects on htaccess seems very intrusive, is there any configuration I'm missing here?
|
I solved it by logging in into admin panel and saving site URL with a trailing slash at the end.
|
252,143 |
<p>I have a snippet in my functions PHP file that allows me to upload SVG files. Since upgrading to the latest version of WP today, I can no longer upload svgs. I also tried a second code snippet from CSS tricks website and that doesn't work either. </p>
<p>Does anyone know a) what may have caused this with the last update and b) Does anyone know a work around.</p>
<p>Here is the code I normally use: </p>
<pre><code>function svg_mime_types( $mimes ) {
mimes['svg'] = 'image/svg+xml';
return $mimes;}
add_filter( 'upload_mimes', 'svg_mime_types' );
</code></pre>
<p>Many thanks</p>
<p>Paul.</p>
|
[
{
"answer_id": 252162,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Seems like this might be related to this ticket <a href=\"https://core.trac.wordpress.org/ticket/39552\">https://core.trac.wordpress.org/ticket/39552</a>, looks like something that got broken in 4.7.1</p>\n"
},
{
"answer_id": 252296,
"author": "Gchtr",
"author_id": 22506,
"author_profile": "https://wordpress.stackexchange.com/users/22506",
"pm_score": 5,
"selected": true,
"text": "<p>In WordPress 4.7.1 <a href=\"https://core.trac.wordpress.org/changeset/39831\" rel=\"noreferrer\">a change was introduced</a> that checks for the real mime type of an uploaded file. This breaks uploading file types like SVG or DOCX. There already exist tickets for this issue in WordPress Core, where you can read more about this:</p>\n\n<ul>\n<li>Some Non-image files fail to upload after 4.7.1 (<a href=\"https://core.trac.wordpress.org/ticket/39550\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/39550</a>)</li>\n<li>SVG upload support broken in 4.7.1 (<a href=\"https://core.trac.wordpress.org/ticket/39552\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/39552</a>)</li>\n</ul>\n\n<p>A <strong>temporary</strong> and recommended workaround (for the time until this issue is fixed) is the following plugin:<br>\n<a href=\"https://wordpress.org/plugins/disable-real-mime-check/\" rel=\"noreferrer\"><strong>Disable Real MIME Check</strong></a></p>\n\n<p>If you don’t want to use that plugin, here’s the same functionality:</p>\n\n<pre><code>add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {\n global $wp_version;\n\n if ( '4.7.2' !== $wp_version ) {\n return $data;\n }\n\n $filetype = wp_check_filetype( $filename, $mimes );\n\n return [\n 'ext' => $filetype['ext'],\n 'type' => $filetype['type'],\n 'proper_filename' => $data['proper_filename']\n ];\n\n}, 10, 4 );\n</code></pre>\n\n<p>Notice that this snipped has a version check included to disable the fix as soon as WordPress is updated.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>The issue was initially set to be fixed in 4.7.2. But since <a href=\"https://wordpress.org/news/2017/01/wordpress-4-7-2-security-release/\" rel=\"noreferrer\">4.7.2 was an urgent security release</a>, the fix didn’t make it into that version. It’s now supposed to be fixed in 4.7.3.</p>\n"
},
{
"answer_id": 253157,
"author": "MrMesees",
"author_id": 108993,
"author_profile": "https://wordpress.stackexchange.com/users/108993",
"pm_score": 2,
"selected": false,
"text": "<p>Nobody seems to have just worked with what is and that's too bad so here's how I handled...</p>\n\n<h3>History / Background</h3>\n\n<p>I created a SVG uploader in 2015 based upon a CSS-Tricks article looking at what was. I Also got grid working for image preview, and used a few other fixes. Simple plugin (IMO file-type plugins should be simple)</p>\n\n<h3>Solution</h3>\n\n<p>There were a few changes for 4.7. The real PITA was that for <code>image/</code> mime types WP is now using GD on the images. To bypass this I set the <code>svg</code> extension to use <code>application/svg+xml</code> so GD wouldn't mess with the file. </p>\n\n<p><strong>Update:</strong> as of 4.7.2 some bright spark broke that too in some cases</p>\n\n<p>Then later via hook we hotwire it back to <code>image/svg+xml</code>. It is the same used in other answers, but we firstly lock it down to our specific case to eliminate effects (is it an SVG file); we can rely on reading <code>$data['ext']</code> (should be cheaper than the function to get file info as only one comparison and one array / hash access).</p>\n\n<p><strong>Update:</strong> as of 4.7.2 <code>$data['ext']</code> is not always set, so we now if it's length is < 1 extract (potentially unsafe) extension from the filename using\n<code>strtolower(end(explode('.', $filename)))</code>. The reason I'm really fighting using FileInfo is that essentially relying on a PHP extension is too opaque and won't always work for everyone (especially not those compiling without or without access to enable extensions if it's not there). I'd like something that works in-lieu of an extension. It's no longer a matter of having the correct information so for those trusting the output of <code>FileInfo</code> and having the extension (I believe it's default in 5.6+) it should work. Also because this is a plugin, it's not modifying core you can turn off this code or unregister the hook.</p>\n\n<p><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin</a></p>\n\n<p>See </p>\n\n<ul>\n<li><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L38\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L38</a></li>\n<li><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L74\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L74</a></li>\n<li><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L23\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L23</a></li>\n<li><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L79\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L79</a></li>\n</ul>\n\n<h3>Other workarounds</h3>\n\n<p>Allowing unfiltered uploads is a horrible solution because as others have said linking to this thread people could upload php files via media uploader (that's bad and if you do it, you should stop and think!)</p>\n\n<p>Forcing every file through any function without checks (Ironically if you have <code>image/</code> in the mime type you can't just have a simple ext check). This has the potential to create far wider reaching effects to solve a relatively niche problem and introduces more work overall (caveat my plugin also introduces more work for admin users to get admin media UI to work)</p>\n\n<p>If we left the mime as application/svg+xml and simply filtered the mime types the image would upload but would AFAIK require fixes to be used as a featured image etc. There is more work to be done on ensuring universal SVG experience so I chose to pick battles carefully.</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] |
I have a snippet in my functions PHP file that allows me to upload SVG files. Since upgrading to the latest version of WP today, I can no longer upload svgs. I also tried a second code snippet from CSS tricks website and that doesn't work either.
Does anyone know a) what may have caused this with the last update and b) Does anyone know a work around.
Here is the code I normally use:
```
function svg_mime_types( $mimes ) {
mimes['svg'] = 'image/svg+xml';
return $mimes;}
add_filter( 'upload_mimes', 'svg_mime_types' );
```
Many thanks
Paul.
|
In WordPress 4.7.1 [a change was introduced](https://core.trac.wordpress.org/changeset/39831) that checks for the real mime type of an uploaded file. This breaks uploading file types like SVG or DOCX. There already exist tickets for this issue in WordPress Core, where you can read more about this:
* Some Non-image files fail to upload after 4.7.1 (<https://core.trac.wordpress.org/ticket/39550>)
* SVG upload support broken in 4.7.1 (<https://core.trac.wordpress.org/ticket/39552>)
A **temporary** and recommended workaround (for the time until this issue is fixed) is the following plugin:
[**Disable Real MIME Check**](https://wordpress.org/plugins/disable-real-mime-check/)
If you don’t want to use that plugin, here’s the same functionality:
```
add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {
global $wp_version;
if ( '4.7.2' !== $wp_version ) {
return $data;
}
$filetype = wp_check_filetype( $filename, $mimes );
return [
'ext' => $filetype['ext'],
'type' => $filetype['type'],
'proper_filename' => $data['proper_filename']
];
}, 10, 4 );
```
Notice that this snipped has a version check included to disable the fix as soon as WordPress is updated.
**Edit**
The issue was initially set to be fixed in 4.7.2. But since [4.7.2 was an urgent security release](https://wordpress.org/news/2017/01/wordpress-4-7-2-security-release/), the fix didn’t make it into that version. It’s now supposed to be fixed in 4.7.3.
|
252,150 |
<p>I have a sidebar with all my post the page only displays one post at a time. I want to display the post that is clicked from the sidebar.</p>
<p>This is the single post display</p>
<pre><code><?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 1
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h1 class=""><?php the_title(); ?></h1>
<div class="the-date"><p><br><?php the_time('F jS, Y') ?></p></div>
<div class=""><p><?php the_content(); ?></p></div>
<?php endwhile ?>
<?php endif ?>
</code></pre>
<p>This is the side bar displaying post i want to populate the post area </p>
<pre><code><?php
$recent_args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'offset' => 1
);
$the_recent = new WP_Query( $recent_args );
if ( $the_recent->have_posts() ) : ?>
<?php while ( $the_recent->have_posts() ) : $the_recent->the_post(); ?>
<div class="more-news">
<a href=""><?php the_title(); ?> </a>
</div>
<hr>
<?php endwhile ?>
<?php endif ?>
</code></pre>
|
[
{
"answer_id": 252162,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Seems like this might be related to this ticket <a href=\"https://core.trac.wordpress.org/ticket/39552\">https://core.trac.wordpress.org/ticket/39552</a>, looks like something that got broken in 4.7.1</p>\n"
},
{
"answer_id": 252296,
"author": "Gchtr",
"author_id": 22506,
"author_profile": "https://wordpress.stackexchange.com/users/22506",
"pm_score": 5,
"selected": true,
"text": "<p>In WordPress 4.7.1 <a href=\"https://core.trac.wordpress.org/changeset/39831\" rel=\"noreferrer\">a change was introduced</a> that checks for the real mime type of an uploaded file. This breaks uploading file types like SVG or DOCX. There already exist tickets for this issue in WordPress Core, where you can read more about this:</p>\n\n<ul>\n<li>Some Non-image files fail to upload after 4.7.1 (<a href=\"https://core.trac.wordpress.org/ticket/39550\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/39550</a>)</li>\n<li>SVG upload support broken in 4.7.1 (<a href=\"https://core.trac.wordpress.org/ticket/39552\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/39552</a>)</li>\n</ul>\n\n<p>A <strong>temporary</strong> and recommended workaround (for the time until this issue is fixed) is the following plugin:<br>\n<a href=\"https://wordpress.org/plugins/disable-real-mime-check/\" rel=\"noreferrer\"><strong>Disable Real MIME Check</strong></a></p>\n\n<p>If you don’t want to use that plugin, here’s the same functionality:</p>\n\n<pre><code>add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {\n global $wp_version;\n\n if ( '4.7.2' !== $wp_version ) {\n return $data;\n }\n\n $filetype = wp_check_filetype( $filename, $mimes );\n\n return [\n 'ext' => $filetype['ext'],\n 'type' => $filetype['type'],\n 'proper_filename' => $data['proper_filename']\n ];\n\n}, 10, 4 );\n</code></pre>\n\n<p>Notice that this snipped has a version check included to disable the fix as soon as WordPress is updated.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>The issue was initially set to be fixed in 4.7.2. But since <a href=\"https://wordpress.org/news/2017/01/wordpress-4-7-2-security-release/\" rel=\"noreferrer\">4.7.2 was an urgent security release</a>, the fix didn’t make it into that version. It’s now supposed to be fixed in 4.7.3.</p>\n"
},
{
"answer_id": 253157,
"author": "MrMesees",
"author_id": 108993,
"author_profile": "https://wordpress.stackexchange.com/users/108993",
"pm_score": 2,
"selected": false,
"text": "<p>Nobody seems to have just worked with what is and that's too bad so here's how I handled...</p>\n\n<h3>History / Background</h3>\n\n<p>I created a SVG uploader in 2015 based upon a CSS-Tricks article looking at what was. I Also got grid working for image preview, and used a few other fixes. Simple plugin (IMO file-type plugins should be simple)</p>\n\n<h3>Solution</h3>\n\n<p>There were a few changes for 4.7. The real PITA was that for <code>image/</code> mime types WP is now using GD on the images. To bypass this I set the <code>svg</code> extension to use <code>application/svg+xml</code> so GD wouldn't mess with the file. </p>\n\n<p><strong>Update:</strong> as of 4.7.2 some bright spark broke that too in some cases</p>\n\n<p>Then later via hook we hotwire it back to <code>image/svg+xml</code>. It is the same used in other answers, but we firstly lock it down to our specific case to eliminate effects (is it an SVG file); we can rely on reading <code>$data['ext']</code> (should be cheaper than the function to get file info as only one comparison and one array / hash access).</p>\n\n<p><strong>Update:</strong> as of 4.7.2 <code>$data['ext']</code> is not always set, so we now if it's length is < 1 extract (potentially unsafe) extension from the filename using\n<code>strtolower(end(explode('.', $filename)))</code>. The reason I'm really fighting using FileInfo is that essentially relying on a PHP extension is too opaque and won't always work for everyone (especially not those compiling without or without access to enable extensions if it's not there). I'd like something that works in-lieu of an extension. It's no longer a matter of having the correct information so for those trusting the output of <code>FileInfo</code> and having the extension (I believe it's default in 5.6+) it should work. Also because this is a plugin, it's not modifying core you can turn off this code or unregister the hook.</p>\n\n<p><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin</a></p>\n\n<p>See </p>\n\n<ul>\n<li><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L38\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L38</a></li>\n<li><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L74\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L74</a></li>\n<li><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L23\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L23</a></li>\n<li><a href=\"https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L79\" rel=\"nofollow noreferrer\">https://github.com/Lewiscowles1986/WordPressSVGPlugin/blob/master/wp-content/plugins/lc-wp-svg/index.php#L79</a></li>\n</ul>\n\n<h3>Other workarounds</h3>\n\n<p>Allowing unfiltered uploads is a horrible solution because as others have said linking to this thread people could upload php files via media uploader (that's bad and if you do it, you should stop and think!)</p>\n\n<p>Forcing every file through any function without checks (Ironically if you have <code>image/</code> in the mime type you can't just have a simple ext check). This has the potential to create far wider reaching effects to solve a relatively niche problem and introduces more work overall (caveat my plugin also introduces more work for admin users to get admin media UI to work)</p>\n\n<p>If we left the mime as application/svg+xml and simply filtered the mime types the image would upload but would AFAIK require fixes to be used as a featured image etc. There is more work to be done on ensuring universal SVG experience so I chose to pick battles carefully.</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2017/01/11
|
[
"https://wordpress.stackexchange.com/questions/252150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63922/"
] |
I have a sidebar with all my post the page only displays one post at a time. I want to display the post that is clicked from the sidebar.
This is the single post display
```
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 1
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h1 class=""><?php the_title(); ?></h1>
<div class="the-date"><p><br><?php the_time('F jS, Y') ?></p></div>
<div class=""><p><?php the_content(); ?></p></div>
<?php endwhile ?>
<?php endif ?>
```
This is the side bar displaying post i want to populate the post area
```
<?php
$recent_args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'offset' => 1
);
$the_recent = new WP_Query( $recent_args );
if ( $the_recent->have_posts() ) : ?>
<?php while ( $the_recent->have_posts() ) : $the_recent->the_post(); ?>
<div class="more-news">
<a href=""><?php the_title(); ?> </a>
</div>
<hr>
<?php endwhile ?>
<?php endif ?>
```
|
In WordPress 4.7.1 [a change was introduced](https://core.trac.wordpress.org/changeset/39831) that checks for the real mime type of an uploaded file. This breaks uploading file types like SVG or DOCX. There already exist tickets for this issue in WordPress Core, where you can read more about this:
* Some Non-image files fail to upload after 4.7.1 (<https://core.trac.wordpress.org/ticket/39550>)
* SVG upload support broken in 4.7.1 (<https://core.trac.wordpress.org/ticket/39552>)
A **temporary** and recommended workaround (for the time until this issue is fixed) is the following plugin:
[**Disable Real MIME Check**](https://wordpress.org/plugins/disable-real-mime-check/)
If you don’t want to use that plugin, here’s the same functionality:
```
add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {
global $wp_version;
if ( '4.7.2' !== $wp_version ) {
return $data;
}
$filetype = wp_check_filetype( $filename, $mimes );
return [
'ext' => $filetype['ext'],
'type' => $filetype['type'],
'proper_filename' => $data['proper_filename']
];
}, 10, 4 );
```
Notice that this snipped has a version check included to disable the fix as soon as WordPress is updated.
**Edit**
The issue was initially set to be fixed in 4.7.2. But since [4.7.2 was an urgent security release](https://wordpress.org/news/2017/01/wordpress-4-7-2-security-release/), the fix didn’t make it into that version. It’s now supposed to be fixed in 4.7.3.
|
252,171 |
<p>I'm having trouble trying to display the current logged in author's first_name even if they haven't published a custom post outside the loop. Could someone get me started please.</p>
|
[
{
"answer_id": 252175,
"author": "Eckstein",
"author_id": 23492,
"author_profile": "https://wordpress.stackexchange.com/users/23492",
"pm_score": 1,
"selected": false,
"text": "<p>This should do it:</p>\n\n<pre><code>$user = get_current_user_id();\n$userdata = get_userdata($user);\n$firstName = $userdata->first_name;\n\necho $firstName;\n</code></pre>\n\n<p>Keep in mind this will only work if a user is logged in, so it's probably good to put a conditional around it to check, like so:</p>\n\n<pre><code>$user=get_current_user_id();\nif($user) {\n $userdata = get_userdata($user);\n $firstName = $userdata->first_name;\n\n echo $firstName;\n}\n</code></pre>\n"
},
{
"answer_id": 252176,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 3,
"selected": true,
"text": "<p>author's name or logged in user's name?</p>\n\n<p>can use <code>global $current_user;</code> or <code>wp_get_current_user();</code> if the user is logged in.</p>\n\n<pre><code>if( is_user_logged_in() ) {\n $current_user = wp_get_current_user();\n echo $current_user->user_firstname;\n}\n</code></pre>\n\n<p>for specific user role you can check <code>$current_user->roles</code> array.</p>\n\n<p>Reference: <br>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_get_current_user</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/get_currentuserinfo\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_currentuserinfo</a></p>\n"
},
{
"answer_id": 252208,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can use below code to retrieve details of current user:</p>\n\n<pre><code><?php \n if(is_user_logged_in() ){\n $current_user = get_currentuserinfo();\n echo 'User first name: ' . $current_user->user_firstname . '<br />';\n }\n?>\n</code></pre>\n"
}
] |
2017/01/12
|
[
"https://wordpress.stackexchange.com/questions/252171",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] |
I'm having trouble trying to display the current logged in author's first\_name even if they haven't published a custom post outside the loop. Could someone get me started please.
|
author's name or logged in user's name?
can use `global $current_user;` or `wp_get_current_user();` if the user is logged in.
```
if( is_user_logged_in() ) {
$current_user = wp_get_current_user();
echo $current_user->user_firstname;
}
```
for specific user role you can check `$current_user->roles` array.
Reference:
<https://codex.wordpress.org/Function_Reference/wp_get_current_user>
<https://codex.wordpress.org/Function_Reference/get_currentuserinfo>
|
252,253 |
<p>I updated Wordpress to 4.7.1 and cant upload SVG anymore.</p>
<p>I had a function in my functions.php file </p>
<pre><code>function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
</code></pre>
<p>but it also dont help now.</p>
|
[
{
"answer_id": 252324,
"author": "Don-Silvermann",
"author_id": 110815,
"author_profile": "https://wordpress.stackexchange.com/users/110815",
"pm_score": 4,
"selected": true,
"text": "<p>Per the thread below, a <strong>temporary solution</strong> would be to add this code to your wp-config file:</p>\n\n<pre><code>define( 'ALLOW_UNFILTERED_UPLOADS', true );\n</code></pre>\n\n<p><a href=\"https://wordpress.org/support/topic/wp-4-7-1-kills-svg/page/3/\" rel=\"noreferrer\">https://wordpress.org/support/topic/wp-4-7-1-kills-svg/page/3/</a></p>\n"
},
{
"answer_id": 252482,
"author": "Don-Silvermann",
"author_id": 110815,
"author_profile": "https://wordpress.stackexchange.com/users/110815",
"pm_score": 0,
"selected": false,
"text": "<p>If you're the only one who has the ability to upload files to WordPress, no. </p>\n\n<p>But if you allow users to register and comment on your blog, yes..</p>\n\n<p>It is a temporary fix to allow you to upload files. Feel free to remove the code after you upload the SVG files.</p>\n"
}
] |
2017/01/12
|
[
"https://wordpress.stackexchange.com/questions/252253",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110781/"
] |
I updated Wordpress to 4.7.1 and cant upload SVG anymore.
I had a function in my functions.php file
```
function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
```
but it also dont help now.
|
Per the thread below, a **temporary solution** would be to add this code to your wp-config file:
```
define( 'ALLOW_UNFILTERED_UPLOADS', true );
```
<https://wordpress.org/support/topic/wp-4-7-1-kills-svg/page/3/>
|
252,255 |
<p>I am trying to learn TDD and am struggling with creating factories for custom objects. For instance, if I have a custom user type and all users of that type must have a specific capability, it's cumbersome to use the WP_UnitTest factory to create a user and then add the capability manually in each test before using the object. Because I need to use these objects in a variety of test files, it would be redundant to have a factory function in each test file/class, and it's a pain to manually implement all four variations of the factory methods (create, create_and_get, create_many, and create_and_get_many).</p>
<p>What is the best way to create a factory for unit test objects like this?</p>
|
[
{
"answer_id": 252324,
"author": "Don-Silvermann",
"author_id": 110815,
"author_profile": "https://wordpress.stackexchange.com/users/110815",
"pm_score": 4,
"selected": true,
"text": "<p>Per the thread below, a <strong>temporary solution</strong> would be to add this code to your wp-config file:</p>\n\n<pre><code>define( 'ALLOW_UNFILTERED_UPLOADS', true );\n</code></pre>\n\n<p><a href=\"https://wordpress.org/support/topic/wp-4-7-1-kills-svg/page/3/\" rel=\"noreferrer\">https://wordpress.org/support/topic/wp-4-7-1-kills-svg/page/3/</a></p>\n"
},
{
"answer_id": 252482,
"author": "Don-Silvermann",
"author_id": 110815,
"author_profile": "https://wordpress.stackexchange.com/users/110815",
"pm_score": 0,
"selected": false,
"text": "<p>If you're the only one who has the ability to upload files to WordPress, no. </p>\n\n<p>But if you allow users to register and comment on your blog, yes..</p>\n\n<p>It is a temporary fix to allow you to upload files. Feel free to remove the code after you upload the SVG files.</p>\n"
}
] |
2017/01/12
|
[
"https://wordpress.stackexchange.com/questions/252255",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38193/"
] |
I am trying to learn TDD and am struggling with creating factories for custom objects. For instance, if I have a custom user type and all users of that type must have a specific capability, it's cumbersome to use the WP\_UnitTest factory to create a user and then add the capability manually in each test before using the object. Because I need to use these objects in a variety of test files, it would be redundant to have a factory function in each test file/class, and it's a pain to manually implement all four variations of the factory methods (create, create\_and\_get, create\_many, and create\_and\_get\_many).
What is the best way to create a factory for unit test objects like this?
|
Per the thread below, a **temporary solution** would be to add this code to your wp-config file:
```
define( 'ALLOW_UNFILTERED_UPLOADS', true );
```
<https://wordpress.org/support/topic/wp-4-7-1-kills-svg/page/3/>
|
252,258 |
<p>I have a shortcode that takes 1 argument for post category slug and returns and list of posts.</p>
<pre><code> //[list-products] creates the product table in the wholesale page, can be used to create a table list of any category
function list_products_func ( $atts ) {
$a = shortcode_atts( array (
'category' => '',
), $atts);
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $a['category']
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query( $args );
echo "<table>";
while ( $products->have_posts() ) {
$products->the_post();
$product = new WC_Product(get_the_ID());
?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a></td>
<td>
<?php echo get_the_excerpt(); ?>
</td>
<td>
<?php echo $product->get_price_html(); ?>
</td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td>
<?php echo woocommerce_template_loop_add_to_cart(); ?>
</td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode ( 'list_products' , 'list_products_func' );
</code></pre>
<p>I'd like it to be able to take any number of categories and return the posts that match BOTH categories. In this use case, it is being used by a coffee distributor to show WooCommerce products that have a category of <code>wholesale</code> and one of their coffee subcategories <code>distinct-well-defined</code> or whatever.</p>
<p>The way it is used is <code>[list-products CAT1 CAT2]</code></p>
<p>I tried just typing the shortcode with commas and hoping the code interpreted that correctly, but that didn't work.</p>
<p>Any help would be appreciated.</p>
<h1>Update</h1>
<p>It turns out I actually need it to filter products so it only shows products that have both categories, not showing all products in both categories.</p>
|
[
{
"answer_id": 252263,
"author": "Robbert",
"author_id": 25834,
"author_profile": "https://wordpress.stackexchange.com/users/25834",
"pm_score": 2,
"selected": true,
"text": "<p>Maybe you can make it so that you can use the shortcode like [list-products categories=\"1,2,3\"], and then explode them as an array to insert them as your terms?</p>\n\n<pre><code><?php\nfunction list_products_func($atts) {\n\n $a = shortcode_atts(array(\n 'categories' => '',\n ), $atts);\n\n // Check for multiple categories by comma\n if ( strpos( $a['categories'], ',' ) !== false ) {\n $terms = explode( $a['categories'] );\n } else {\n $terms = $a['categories'];\n }\n\n $args = array(\n 'posts_per_page' => -1,\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $terms // Your exploded terms array \n )\n ),\n 'post_type' => 'product',\n 'orderby' => 'title,'\n );\n\n $products = new WP_Query($args);\n echo \"<table>\";\n while ($products->have_posts()) {\n\n $products->the_post();\n $product = new WC_Product(get_the_ID()); ?>\n <tr class=\"product-list-item\">\n <td><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></td>\n <td><?php echo get_the_excerpt(); ?></td>\n <td><?php echo $product->get_price_html(); ?></td>\n <td>\n <?php echo woocommerce_quantity_input(\n array(\n 'min_value' => 1,\n 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),\n )); ?>\n </td>\n <td><?php echo woocommerce_template_loop_add_to_cart(); ?></td>\n </tr>\n <?php\n\n }\n echo \"</table>\";\n}\nadd_shortcode('list_products', 'list_products_func');\n?>\n</code></pre>\n"
},
{
"answer_id": 252272,
"author": "Khaled Allen",
"author_id": 110308,
"author_profile": "https://wordpress.stackexchange.com/users/110308",
"pm_score": 0,
"selected": false,
"text": "<p>This is an answer to the second part of my question, which I didn't realize until after the accepted answer came in.</p>\n\n<p>First, I added the accepted answer from Robbert and this little <code>for</code> loop to expand the <code>tax_query</code> arguments dynamically:</p>\n\n<pre><code>//Generates an array of tax_query arguments\n $query_args = array ();\n foreach ( $terms as $term ) {\n array_push( $query_args, array (\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $term\n )\n );\n }\n\n $args = array(\n 'posts_per_page' => -1,\n 'tax_query' => array(\n 'relation' => 'AND',\n $query_args\n ),\n 'post_type' => 'product',\n 'orderby' => 'title,'\n );\n</code></pre>\n"
}
] |
2017/01/12
|
[
"https://wordpress.stackexchange.com/questions/252258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110308/"
] |
I have a shortcode that takes 1 argument for post category slug and returns and list of posts.
```
//[list-products] creates the product table in the wholesale page, can be used to create a table list of any category
function list_products_func ( $atts ) {
$a = shortcode_atts( array (
'category' => '',
), $atts);
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $a['category']
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query( $args );
echo "<table>";
while ( $products->have_posts() ) {
$products->the_post();
$product = new WC_Product(get_the_ID());
?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a></td>
<td>
<?php echo get_the_excerpt(); ?>
</td>
<td>
<?php echo $product->get_price_html(); ?>
</td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td>
<?php echo woocommerce_template_loop_add_to_cart(); ?>
</td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode ( 'list_products' , 'list_products_func' );
```
I'd like it to be able to take any number of categories and return the posts that match BOTH categories. In this use case, it is being used by a coffee distributor to show WooCommerce products that have a category of `wholesale` and one of their coffee subcategories `distinct-well-defined` or whatever.
The way it is used is `[list-products CAT1 CAT2]`
I tried just typing the shortcode with commas and hoping the code interpreted that correctly, but that didn't work.
Any help would be appreciated.
Update
======
It turns out I actually need it to filter products so it only shows products that have both categories, not showing all products in both categories.
|
Maybe you can make it so that you can use the shortcode like [list-products categories="1,2,3"], and then explode them as an array to insert them as your terms?
```
<?php
function list_products_func($atts) {
$a = shortcode_atts(array(
'categories' => '',
), $atts);
// Check for multiple categories by comma
if ( strpos( $a['categories'], ',' ) !== false ) {
$terms = explode( $a['categories'] );
} else {
$terms = $a['categories'];
}
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $terms // Your exploded terms array
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query($args);
echo "<table>";
while ($products->have_posts()) {
$products->the_post();
$product = new WC_Product(get_the_ID()); ?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
<td><?php echo get_the_excerpt(); ?></td>
<td><?php echo $product->get_price_html(); ?></td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td><?php echo woocommerce_template_loop_add_to_cart(); ?></td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode('list_products', 'list_products_func');
?>
```
|
252,260 |
<p>For some reason, I am battling to make sense of everything. This is my code on paste bin: <a href="http://pastebin.com/dJxGS6x6" rel="nofollow noreferrer">http://pastebin.com/dJxGS6x6</a></p>
<p>I want to be able to retrieve the options that are saved in the fields. This does not return anything: </p>
<pre><code><a href="<?php echo get_option('contact_details_vimeo_render'); ?>" target="_blank">
<i class="fa fa-vimeo" aria-hidden="true"></i>
</a>
</code></pre>
<p>I basically want to be able to retrieve the stored data as desired. </p>
|
[
{
"answer_id": 252263,
"author": "Robbert",
"author_id": 25834,
"author_profile": "https://wordpress.stackexchange.com/users/25834",
"pm_score": 2,
"selected": true,
"text": "<p>Maybe you can make it so that you can use the shortcode like [list-products categories=\"1,2,3\"], and then explode them as an array to insert them as your terms?</p>\n\n<pre><code><?php\nfunction list_products_func($atts) {\n\n $a = shortcode_atts(array(\n 'categories' => '',\n ), $atts);\n\n // Check for multiple categories by comma\n if ( strpos( $a['categories'], ',' ) !== false ) {\n $terms = explode( $a['categories'] );\n } else {\n $terms = $a['categories'];\n }\n\n $args = array(\n 'posts_per_page' => -1,\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $terms // Your exploded terms array \n )\n ),\n 'post_type' => 'product',\n 'orderby' => 'title,'\n );\n\n $products = new WP_Query($args);\n echo \"<table>\";\n while ($products->have_posts()) {\n\n $products->the_post();\n $product = new WC_Product(get_the_ID()); ?>\n <tr class=\"product-list-item\">\n <td><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></td>\n <td><?php echo get_the_excerpt(); ?></td>\n <td><?php echo $product->get_price_html(); ?></td>\n <td>\n <?php echo woocommerce_quantity_input(\n array(\n 'min_value' => 1,\n 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),\n )); ?>\n </td>\n <td><?php echo woocommerce_template_loop_add_to_cart(); ?></td>\n </tr>\n <?php\n\n }\n echo \"</table>\";\n}\nadd_shortcode('list_products', 'list_products_func');\n?>\n</code></pre>\n"
},
{
"answer_id": 252272,
"author": "Khaled Allen",
"author_id": 110308,
"author_profile": "https://wordpress.stackexchange.com/users/110308",
"pm_score": 0,
"selected": false,
"text": "<p>This is an answer to the second part of my question, which I didn't realize until after the accepted answer came in.</p>\n\n<p>First, I added the accepted answer from Robbert and this little <code>for</code> loop to expand the <code>tax_query</code> arguments dynamically:</p>\n\n<pre><code>//Generates an array of tax_query arguments\n $query_args = array ();\n foreach ( $terms as $term ) {\n array_push( $query_args, array (\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $term\n )\n );\n }\n\n $args = array(\n 'posts_per_page' => -1,\n 'tax_query' => array(\n 'relation' => 'AND',\n $query_args\n ),\n 'post_type' => 'product',\n 'orderby' => 'title,'\n );\n</code></pre>\n"
}
] |
2017/01/12
|
[
"https://wordpress.stackexchange.com/questions/252260",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
For some reason, I am battling to make sense of everything. This is my code on paste bin: <http://pastebin.com/dJxGS6x6>
I want to be able to retrieve the options that are saved in the fields. This does not return anything:
```
<a href="<?php echo get_option('contact_details_vimeo_render'); ?>" target="_blank">
<i class="fa fa-vimeo" aria-hidden="true"></i>
</a>
```
I basically want to be able to retrieve the stored data as desired.
|
Maybe you can make it so that you can use the shortcode like [list-products categories="1,2,3"], and then explode them as an array to insert them as your terms?
```
<?php
function list_products_func($atts) {
$a = shortcode_atts(array(
'categories' => '',
), $atts);
// Check for multiple categories by comma
if ( strpos( $a['categories'], ',' ) !== false ) {
$terms = explode( $a['categories'] );
} else {
$terms = $a['categories'];
}
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $terms // Your exploded terms array
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query($args);
echo "<table>";
while ($products->have_posts()) {
$products->the_post();
$product = new WC_Product(get_the_ID()); ?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
<td><?php echo get_the_excerpt(); ?></td>
<td><?php echo $product->get_price_html(); ?></td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td><?php echo woocommerce_template_loop_add_to_cart(); ?></td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode('list_products', 'list_products_func');
?>
```
|
252,262 |
<p>I am just beginning a page, and for my current purposes it seems that the only extra things I need are a couple of extra fields for posts of a certain category. Because I only need to add a little information, I think that it might be appropriate to give posts belonging to this category custom fields using Advanced Custom Fields (aka ACF). However, I was thinking that later I might discover it is better to use custom post types, that have the fields built into the structure of the custom post type. </p>
<p>For example, imagine I originally start with normal posts, and I assign them all to the category of "movie". I give them each post in the category movie the custom field called "director" and populate it with the appropriate director. Then, later, if I want to create a custom post type, that has the field "director" as part of the custom post-type I create called "MovieType", could I easily transfer the directors in the custom fields for every old "normal post" of category "movie" to be imported to the new custom post type?</p>
<p>I am concerned it might not be easy to export this data to a custom post type later and I don't want to have to manually copy/paste or enter all the fields from my custom fields to the fields of the new custom post type. </p>
<p><strong>The question: what is the easiest way to convert standard posts with custom fields into a new custom post type, AND to import/keep the data originally assigned to each post from the custom field into the native field of a new post type? Can this be done automatically?</strong></p>
<p>Thanks!</p>
|
[
{
"answer_id": 252263,
"author": "Robbert",
"author_id": 25834,
"author_profile": "https://wordpress.stackexchange.com/users/25834",
"pm_score": 2,
"selected": true,
"text": "<p>Maybe you can make it so that you can use the shortcode like [list-products categories=\"1,2,3\"], and then explode them as an array to insert them as your terms?</p>\n\n<pre><code><?php\nfunction list_products_func($atts) {\n\n $a = shortcode_atts(array(\n 'categories' => '',\n ), $atts);\n\n // Check for multiple categories by comma\n if ( strpos( $a['categories'], ',' ) !== false ) {\n $terms = explode( $a['categories'] );\n } else {\n $terms = $a['categories'];\n }\n\n $args = array(\n 'posts_per_page' => -1,\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $terms // Your exploded terms array \n )\n ),\n 'post_type' => 'product',\n 'orderby' => 'title,'\n );\n\n $products = new WP_Query($args);\n echo \"<table>\";\n while ($products->have_posts()) {\n\n $products->the_post();\n $product = new WC_Product(get_the_ID()); ?>\n <tr class=\"product-list-item\">\n <td><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></td>\n <td><?php echo get_the_excerpt(); ?></td>\n <td><?php echo $product->get_price_html(); ?></td>\n <td>\n <?php echo woocommerce_quantity_input(\n array(\n 'min_value' => 1,\n 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),\n )); ?>\n </td>\n <td><?php echo woocommerce_template_loop_add_to_cart(); ?></td>\n </tr>\n <?php\n\n }\n echo \"</table>\";\n}\nadd_shortcode('list_products', 'list_products_func');\n?>\n</code></pre>\n"
},
{
"answer_id": 252272,
"author": "Khaled Allen",
"author_id": 110308,
"author_profile": "https://wordpress.stackexchange.com/users/110308",
"pm_score": 0,
"selected": false,
"text": "<p>This is an answer to the second part of my question, which I didn't realize until after the accepted answer came in.</p>\n\n<p>First, I added the accepted answer from Robbert and this little <code>for</code> loop to expand the <code>tax_query</code> arguments dynamically:</p>\n\n<pre><code>//Generates an array of tax_query arguments\n $query_args = array ();\n foreach ( $terms as $term ) {\n array_push( $query_args, array (\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => $term\n )\n );\n }\n\n $args = array(\n 'posts_per_page' => -1,\n 'tax_query' => array(\n 'relation' => 'AND',\n $query_args\n ),\n 'post_type' => 'product',\n 'orderby' => 'title,'\n );\n</code></pre>\n"
}
] |
2017/01/12
|
[
"https://wordpress.stackexchange.com/questions/252262",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
] |
I am just beginning a page, and for my current purposes it seems that the only extra things I need are a couple of extra fields for posts of a certain category. Because I only need to add a little information, I think that it might be appropriate to give posts belonging to this category custom fields using Advanced Custom Fields (aka ACF). However, I was thinking that later I might discover it is better to use custom post types, that have the fields built into the structure of the custom post type.
For example, imagine I originally start with normal posts, and I assign them all to the category of "movie". I give them each post in the category movie the custom field called "director" and populate it with the appropriate director. Then, later, if I want to create a custom post type, that has the field "director" as part of the custom post-type I create called "MovieType", could I easily transfer the directors in the custom fields for every old "normal post" of category "movie" to be imported to the new custom post type?
I am concerned it might not be easy to export this data to a custom post type later and I don't want to have to manually copy/paste or enter all the fields from my custom fields to the fields of the new custom post type.
**The question: what is the easiest way to convert standard posts with custom fields into a new custom post type, AND to import/keep the data originally assigned to each post from the custom field into the native field of a new post type? Can this be done automatically?**
Thanks!
|
Maybe you can make it so that you can use the shortcode like [list-products categories="1,2,3"], and then explode them as an array to insert them as your terms?
```
<?php
function list_products_func($atts) {
$a = shortcode_atts(array(
'categories' => '',
), $atts);
// Check for multiple categories by comma
if ( strpos( $a['categories'], ',' ) !== false ) {
$terms = explode( $a['categories'] );
} else {
$terms = $a['categories'];
}
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $terms // Your exploded terms array
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query($args);
echo "<table>";
while ($products->have_posts()) {
$products->the_post();
$product = new WC_Product(get_the_ID()); ?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
<td><?php echo get_the_excerpt(); ?></td>
<td><?php echo $product->get_price_html(); ?></td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td><?php echo woocommerce_template_loop_add_to_cart(); ?></td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode('list_products', 'list_products_func');
?>
```
|
252,277 |
<p>I'm still a noob with php but I'm trying to display a different layout for my Wordpress webpage for a single post id. </p>
<p>I thought it would have been simple but I've tried a quiet few variations of the code below. Including <code>is_singular</code> and without the <code>$post</code> etc. and I've ran out of inspiration. What can I do? What do I need to look for? Can anyone help me out?</p>
<pre><code><?php
if (is_single ($post = '2578')) {
get_template_part('partials/content', 'challenge');
}
elseif (is_single ($post = '')) {
get_template_part('partials/challenge/content', 'challenge-2');
get_template_part('partials/challenge/content', 'categories');
get_template_part('partials/challenge/content', 'snake-checklist');
get_template_part('partials/challenge/content', 'timeline');
}?>
</code></pre>
|
[
{
"answer_id": 252286,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": false,
"text": "<p>This looks almost correct. Let's have a look at <a href=\"https://developer.wordpress.org/reference/functions/is_single/\" rel=\"noreferrer\"><code>is_single()</code></a>:</p>\n\n<blockquote>\n <p>Works for any post type, <strong>except attachments and pages</strong>...</p>\n</blockquote>\n\n<p>So if the given ID isn't that of a <code>page</code> or <code>attachment</code> post type then you can use the function as so:</p>\n\n<pre><code>if( is_single( 2578 ) ) {\n /* ... */\n} else {\n /* ... */\n}\n</code></pre>\n\n<p>Otherwise, if the ID is a <code>page</code> post type you can use <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"noreferrer\"><code>is_page()</code></a></p>\n\n<pre><code>if( is_page( 2578 ) ) {\n /* ... */\n}\n</code></pre>\n\n<p>Should the ID be that of an <code>attachment</code> page you may use <a href=\"https://developer.wordpress.org/reference/functions/is_attachment/\" rel=\"noreferrer\"><code>is_attachment()</code></a></p>\n\n<pre><code>if( is_attachment( 2578 ) ) {\n /* ... */\n}\n</code></pre>\n\n<p>Finally, if you're unsure of the post type you could check against the <code>global $post</code> object, assuming it is correct:</p>\n\n<pre><code>global $post;\nif( is_object( $post ) && 2578 == $post->ID ) {\n /* ... */\n}\n</code></pre>\n"
},
{
"answer_id": 260515,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 2,
"selected": false,
"text": "<p>The function <code>get_the_ID()</code> will work regardless of post type (if it's a page, post, or custom post). </p>\n\n<p>You could use that function to perform your conditional check.</p>\n\n<pre><code>if ( get_the_ID() === 2578) {\n get_template_part('partials/content', 'challenge');\n} \nelse{\n // Add other template calls, or additional conditions, is_single, is_archive, etc.\n}?>\n</code></pre>\n\n<p>Noting that this function won't work on archives since they don't have ID's.</p>\n"
},
{
"answer_id": 309097,
"author": "Paweł Sala",
"author_id": 147256,
"author_profile": "https://wordpress.stackexchange.com/users/147256",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php if( $post->ID == 21) { ?>\n <?php include('file_1.php'); ?>\n<?php } else { ?>\n <?php include('file_2.php'); ?>\n<?php } ?>\n</code></pre>\n"
}
] |
2017/01/12
|
[
"https://wordpress.stackexchange.com/questions/252277",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110792/"
] |
I'm still a noob with php but I'm trying to display a different layout for my Wordpress webpage for a single post id.
I thought it would have been simple but I've tried a quiet few variations of the code below. Including `is_singular` and without the `$post` etc. and I've ran out of inspiration. What can I do? What do I need to look for? Can anyone help me out?
```
<?php
if (is_single ($post = '2578')) {
get_template_part('partials/content', 'challenge');
}
elseif (is_single ($post = '')) {
get_template_part('partials/challenge/content', 'challenge-2');
get_template_part('partials/challenge/content', 'categories');
get_template_part('partials/challenge/content', 'snake-checklist');
get_template_part('partials/challenge/content', 'timeline');
}?>
```
|
This looks almost correct. Let's have a look at [`is_single()`](https://developer.wordpress.org/reference/functions/is_single/):
>
> Works for any post type, **except attachments and pages**...
>
>
>
So if the given ID isn't that of a `page` or `attachment` post type then you can use the function as so:
```
if( is_single( 2578 ) ) {
/* ... */
} else {
/* ... */
}
```
Otherwise, if the ID is a `page` post type you can use [`is_page()`](https://developer.wordpress.org/reference/functions/is_page/)
```
if( is_page( 2578 ) ) {
/* ... */
}
```
Should the ID be that of an `attachment` page you may use [`is_attachment()`](https://developer.wordpress.org/reference/functions/is_attachment/)
```
if( is_attachment( 2578 ) ) {
/* ... */
}
```
Finally, if you're unsure of the post type you could check against the `global $post` object, assuming it is correct:
```
global $post;
if( is_object( $post ) && 2578 == $post->ID ) {
/* ... */
}
```
|
252,300 |
<p>I'm very new to WordPress Development and I'm attempting to make a custom post type business directory style plugin in my plugins folder for my site, but everytime I activate it I get the white screen of death over my entire web site. I've definitely tracked it down to this plugin but I can't see what I've done that's causing it.</p>
<pre><code><?php
/*
Plugin Name: Special Coffee CPT
Plugin URI: http://danijoypractice.x10host.com
Description: This plugin creates a custom post type & template page
Author: Danielle Rautiainen
Version: 1.0
Author URI: http://danijoypractice.x10host.com
*/
add_action('init', 'local_business_directory_register');
function local_business_directory_register() {
$args = array(
'label' => __('Business Directory'),
'singular_label' => __('Business'),
'public' => true,
'taxonomies' => array('category'),
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => true,
'has_archive' => true,
'supports' => array('title', 'editor', ),
'rewrite' => array('slug' => 'businesses', 'with_front' => false),
);
}
register_post_type( 'businesses' , $args );
register_taxonomy("business-type", array("businesses"), array(
"hierarchical" => true,
"label" => "Business Type",
"singular_label" => "Business Type",
"rewrite" => true
)
);
add_action("admin_init", "local_business_directory_meta");
function local_business_directory_meta ()
{
add_meta_box("business-meta", "Business Options", "local_business_directory_options", "businesses", "normal", "high");
}
function local_business_directory_options()
{
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
$custom = get_post_custom($post->ID);
$address = $custom["address"][0];
$website = $custom["website"][0];
$phone = $custom["phone"][0];
?>
<style type="text/css">
<?php include('business-directory.css'); ?>
</style>
<div class="business_directory_extras">
<?php $website= ($website == "") ? "http://" : $website; ?>
<div>
<label>Website:</label>
<input name="website" value="<?php echo $website; ?>" />
</div>
<div>
<label>Phone:</label>
<input name="phone" value="<?php echo $phone; ?>" />
</div>
<div>
<label>Address:</label>
<textarea name="address"><?php echo $address; ?>" /></textarea>
</div>
</div>
<?php
}
add_action('save_post', 'local_business_directory_save_extras');
function business_manager_save_extras(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return $post_id;
}else{
update_post_meta($post->ID, "website", $_POST["website"]);
update_post_meta($post->ID, "address", $_POST["address"]);
update_post_meta($post->ID, "phone", $_POST["phone"]);
}
}
?>
</code></pre>
<p>Am I missing something? Any help would be very appreciated!</p>
|
[
{
"answer_id": 252286,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": false,
"text": "<p>This looks almost correct. Let's have a look at <a href=\"https://developer.wordpress.org/reference/functions/is_single/\" rel=\"noreferrer\"><code>is_single()</code></a>:</p>\n\n<blockquote>\n <p>Works for any post type, <strong>except attachments and pages</strong>...</p>\n</blockquote>\n\n<p>So if the given ID isn't that of a <code>page</code> or <code>attachment</code> post type then you can use the function as so:</p>\n\n<pre><code>if( is_single( 2578 ) ) {\n /* ... */\n} else {\n /* ... */\n}\n</code></pre>\n\n<p>Otherwise, if the ID is a <code>page</code> post type you can use <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"noreferrer\"><code>is_page()</code></a></p>\n\n<pre><code>if( is_page( 2578 ) ) {\n /* ... */\n}\n</code></pre>\n\n<p>Should the ID be that of an <code>attachment</code> page you may use <a href=\"https://developer.wordpress.org/reference/functions/is_attachment/\" rel=\"noreferrer\"><code>is_attachment()</code></a></p>\n\n<pre><code>if( is_attachment( 2578 ) ) {\n /* ... */\n}\n</code></pre>\n\n<p>Finally, if you're unsure of the post type you could check against the <code>global $post</code> object, assuming it is correct:</p>\n\n<pre><code>global $post;\nif( is_object( $post ) && 2578 == $post->ID ) {\n /* ... */\n}\n</code></pre>\n"
},
{
"answer_id": 260515,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 2,
"selected": false,
"text": "<p>The function <code>get_the_ID()</code> will work regardless of post type (if it's a page, post, or custom post). </p>\n\n<p>You could use that function to perform your conditional check.</p>\n\n<pre><code>if ( get_the_ID() === 2578) {\n get_template_part('partials/content', 'challenge');\n} \nelse{\n // Add other template calls, or additional conditions, is_single, is_archive, etc.\n}?>\n</code></pre>\n\n<p>Noting that this function won't work on archives since they don't have ID's.</p>\n"
},
{
"answer_id": 309097,
"author": "Paweł Sala",
"author_id": 147256,
"author_profile": "https://wordpress.stackexchange.com/users/147256",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php if( $post->ID == 21) { ?>\n <?php include('file_1.php'); ?>\n<?php } else { ?>\n <?php include('file_2.php'); ?>\n<?php } ?>\n</code></pre>\n"
}
] |
2017/01/12
|
[
"https://wordpress.stackexchange.com/questions/252300",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110800/"
] |
I'm very new to WordPress Development and I'm attempting to make a custom post type business directory style plugin in my plugins folder for my site, but everytime I activate it I get the white screen of death over my entire web site. I've definitely tracked it down to this plugin but I can't see what I've done that's causing it.
```
<?php
/*
Plugin Name: Special Coffee CPT
Plugin URI: http://danijoypractice.x10host.com
Description: This plugin creates a custom post type & template page
Author: Danielle Rautiainen
Version: 1.0
Author URI: http://danijoypractice.x10host.com
*/
add_action('init', 'local_business_directory_register');
function local_business_directory_register() {
$args = array(
'label' => __('Business Directory'),
'singular_label' => __('Business'),
'public' => true,
'taxonomies' => array('category'),
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => true,
'has_archive' => true,
'supports' => array('title', 'editor', ),
'rewrite' => array('slug' => 'businesses', 'with_front' => false),
);
}
register_post_type( 'businesses' , $args );
register_taxonomy("business-type", array("businesses"), array(
"hierarchical" => true,
"label" => "Business Type",
"singular_label" => "Business Type",
"rewrite" => true
)
);
add_action("admin_init", "local_business_directory_meta");
function local_business_directory_meta ()
{
add_meta_box("business-meta", "Business Options", "local_business_directory_options", "businesses", "normal", "high");
}
function local_business_directory_options()
{
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
$custom = get_post_custom($post->ID);
$address = $custom["address"][0];
$website = $custom["website"][0];
$phone = $custom["phone"][0];
?>
<style type="text/css">
<?php include('business-directory.css'); ?>
</style>
<div class="business_directory_extras">
<?php $website= ($website == "") ? "http://" : $website; ?>
<div>
<label>Website:</label>
<input name="website" value="<?php echo $website; ?>" />
</div>
<div>
<label>Phone:</label>
<input name="phone" value="<?php echo $phone; ?>" />
</div>
<div>
<label>Address:</label>
<textarea name="address"><?php echo $address; ?>" /></textarea>
</div>
</div>
<?php
}
add_action('save_post', 'local_business_directory_save_extras');
function business_manager_save_extras(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return $post_id;
}else{
update_post_meta($post->ID, "website", $_POST["website"]);
update_post_meta($post->ID, "address", $_POST["address"]);
update_post_meta($post->ID, "phone", $_POST["phone"]);
}
}
?>
```
Am I missing something? Any help would be very appreciated!
|
This looks almost correct. Let's have a look at [`is_single()`](https://developer.wordpress.org/reference/functions/is_single/):
>
> Works for any post type, **except attachments and pages**...
>
>
>
So if the given ID isn't that of a `page` or `attachment` post type then you can use the function as so:
```
if( is_single( 2578 ) ) {
/* ... */
} else {
/* ... */
}
```
Otherwise, if the ID is a `page` post type you can use [`is_page()`](https://developer.wordpress.org/reference/functions/is_page/)
```
if( is_page( 2578 ) ) {
/* ... */
}
```
Should the ID be that of an `attachment` page you may use [`is_attachment()`](https://developer.wordpress.org/reference/functions/is_attachment/)
```
if( is_attachment( 2578 ) ) {
/* ... */
}
```
Finally, if you're unsure of the post type you could check against the `global $post` object, assuming it is correct:
```
global $post;
if( is_object( $post ) && 2578 == $post->ID ) {
/* ... */
}
```
|
252,328 |
<p>I have upgraded my WordPress to <code>4.7.1</code>, and after that I've tried to enumerate users through REST API, which should be fixed, but I was able to retrieve users.</p>
<pre><code>https://mywebsite.com/wp-json/wp/v2/users
</code></pre>
<p>Output:</p>
<pre><code>[{"id":1,"name":"admin","url":"","description":"","link":"https:\/\/mywebsite\/author\/admin\/","slug":"admin","avatar_urls":{"24": ...
</code></pre>
<p>Changelog from latest version:</p>
<blockquote>
<p>The REST API exposed user data for all users who had authored a post
of a public post type. WordPress 4.7.1 limits this to only post types
which have specified that they should be shown within the REST API.
Reported by Krogsgard and Chris Jean.</p>
</blockquote>
<p>After installing plugin <code>Disable REST API</code>, it seems that everything is working fine, but I don't like to use for every little thing plugin.</p>
<p>The output after using plugin is:</p>
<pre><code>{"code":"rest_cannot_access","message":"Only authenticated users can access the REST API.","data":{"status":401}}
</code></pre>
<p>How can I fix this issue without using plugin, or why even after upgrading this stil exist?</p>
<p><strong>EDIT 30.9.2017</strong></p>
<p>I realized that there is a conflict between <code>contact 7</code> plugin and <code>Disable REST API</code> and that will give you <code>401 unauthorized</code> error.</p>
<p>When you try to send a message through <code>contact 7</code> form, it will make a request </p>
<pre><code>wp-json/contact-form-7/v1/contact-forms/258/feedback
</code></pre>
<p>and disabling that is not a good idea.</p>
|
[
{
"answer_id": 254251,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 6,
"selected": true,
"text": "<p>This code snippet will hide the users, posts, and comments endpoint results and give 404 as the result, while the rest of the API calls keep running as they were.</p>\n<p><strong>::UPDATE::</strong></p>\n<pre><code>add_filter('rest_endpoints', function(){\n $toRemove = ['users', 'posts', 'comments'];\n foreach($toRemove as $val)\n {\n if (isset($endpoints['/wp/v2/'.$val])) {\n unset($endpoints['/wp/v2/'.$val]);\n }\n\n if(isset($endpoints['/wp/v2/'.$val.'/(?P<id>[\\d]+)'])) {\n unset($endpoints['/wp/v2/'.$val.'/(?P<id>[\\d]+)']);\n }\n } \n return $endpoints;\n});\n</code></pre>\n<p><strong>::UPDATE::</strong></p>\n<p>This snippet will remove all the default endpoints.</p>\n<p><code><?php remove_action('rest_api_init', 'create_initial_rest_routes', 99); ?></code></p>\n"
},
{
"answer_id": 270499,
"author": "lowtechsun",
"author_id": 77054,
"author_profile": "https://wordpress.stackexchange.com/users/77054",
"pm_score": 2,
"selected": false,
"text": "<p>Remove the API link from the HTML head if you like.</p>\n\n<pre><code>// https://wordpress.stackexchange.com/a/211469/77054\n// https://wordpress.stackexchange.com/a/212472\nremove_action( 'wp_head', 'rest_output_link_wp_head', 10 );\n</code></pre>\n\n<p>Then require authentication for all requests. </p>\n\n<pre><code>// You can require authentication for all REST API requests by adding an is_user_logged_in check to the rest_authentication_errors filter.\nadd_filter( 'rest_authentication_errors', function( $result ) {\n if ( ! empty( $result ) ) {\n return $result;\n }\n if ( ! is_user_logged_in() ) {\n return new WP_Error( 'rest_not_logged_in', 'Only authenticated users can access the REST API.', array( 'status' => 401 ) );\n }\n return $result;\n});\n</code></pre>\n\n<p>This will leave you with the desired message.</p>\n\n<p>Now to stop enumeration you could use something like this.</p>\n\n<pre><code>// https://perishablepress.com/stop-user-enumeration-wordpress/\n// block WP enum scans\n // https://m0n.co/enum\n if (!is_admin()) {\n // default URL format\n if (preg_match('/author=([0-9]*)/i', $_SERVER['QUERY_STRING'])) die();\n add_filter('redirect_canonical', 'shapeSpace_check_enum', 10, 2);\n }\n function shapeSpace_check_enum($redirect, $request) {\n // permalink URL format\n if (preg_match('/\\?author=([0-9]*)(\\/*)/i', $request)) die();\n else return $redirect;\n }\n</code></pre>\n\n<p>Check out the whole post for further techniques.</p>\n"
},
{
"answer_id": 271229,
"author": "Foo",
"author_id": 122532,
"author_profile": "https://wordpress.stackexchange.com/users/122532",
"pm_score": -1,
"selected": false,
"text": "<p>To be able to fix this you first need to know the source of the problem.</p>\n\n<ol>\n<li>Do you use SEO plugins like: All in one SEO pack or Yoast? Try to disable this and check again.</li>\n<li>Do you use the Jetpack plugin? Try to disable this and check again.</li>\n</ol>\n\n<p>Please let me know if this pointed you into the right direction. </p>\n\n<p>A dirty way to solve this is to just block the url underneath in your .htacces.\n<a href=\"https://mywebsite.com/wp-json/wp/v2/users\" rel=\"nofollow noreferrer\">https://mywebsite.com/wp-json/wp/v2/users</a></p>\n"
},
{
"answer_id": 321745,
"author": "vim",
"author_id": 155827,
"author_profile": "https://wordpress.stackexchange.com/users/155827",
"pm_score": 1,
"selected": false,
"text": "<p>You can fix it through nginx/apache config:</p>\n\n<pre><code>location ~* /wp-json/wp/v2/users {\n allow ip_address;\n deny all;\n}\n</code></pre>\n"
},
{
"answer_id": 371045,
"author": "Time Killer",
"author_id": 185828,
"author_profile": "https://wordpress.stackexchange.com/users/185828",
"pm_score": 1,
"selected": false,
"text": "<p>just another answer:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'rest_user_query', '__return_null' );\nadd_filter( 'rest_prepare_user', '__return_null' );\n</code></pre>\n"
},
{
"answer_id": 378142,
"author": "drzraf",
"author_id": 197528,
"author_profile": "https://wordpress.stackexchange.com/users/197528",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-php prettyprint-override\"><code>/**\n * Wrap an existing default callback passed in parameter and create\n * a new permission callback introducing preliminary checks and\n * falling-back on the default callback in case of success.\n */\nfunction permission_callback_hardener ($existing_callback) {\n return function ($request) use($existing_callback) {\n if (! current_user_can('list_users')) {\n return new WP_Error(\n 'rest_user_cannot_view',\n __( 'Sorry, you are not allowed to access users.' ),\n [ 'status' => rest_authorization_required_code() ]\n );\n }\n\n return $existing_callback($request);\n };\n}\n\nfunction api_users_endpoint_force_auth($endpoints)\n{\n $users_get_route = &$endpoints['/wp/v2/users'][0];\n $users_get_route['permission_callback'] = permission_callback_hardener($users_get_route['permission_callback']);\n\n $user_get_route = &$endpoints['/wp/v2/users/(?P<id>[\\d]+)'][0];\n $user_get_route['permission_callback'] = permission_callback_hardener($user_get_route['permission_callback']);\n\n return $endpoints;\n}\n\nadd_filter('rest_endpoints', 'api_users_endpoint_force_auth');\n</code></pre>\n<ul>\n<li>The endpoint(s) is not blocked for administrators (Gutenberg keeps working)</li>\n<li>The endpoint rejects anonymous users in a proper way.</li>\n<li>It's generic enough to support further endpoints.</li>\n<li>The <code>current_user_can</code> could be further enhanced, made more generic.</li>\n<li>Assume that the <code>GET</code> method is the first for a registered route (which so far has always been true)</li>\n</ul>\n"
},
{
"answer_id": 379682,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": 1,
"selected": false,
"text": "<p>.htaccess code to block all author scans</p>\n<pre><code># BEGIN block author scans\nRewriteEngine On\nRewriteBase /\nRewriteCond %{QUERY_STRING} (author=\\d+) [NC]\nRewriteRule .* - [F]\n# END block author scans\n</code></pre>\n<p>You can remove it by function as the accepted answer suggested</p>\n"
},
{
"answer_id": 380954,
"author": "Mickael Bertainchant",
"author_id": 194938,
"author_profile": "https://wordpress.stackexchange.com/users/194938",
"pm_score": 1,
"selected": false,
"text": "<p>I used this little code in function.php :</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * API REST access only for administrators\n *\n * @return void\n */\n function api_rest_only_for_admin_users() {\n $current_user = wp_get_current_user();\n if ( in_array('administrator', $current_user->roles ) ) {\n return;\n } else {\n wp_die('Sorry you are not allowed to access this data','API REST Forbidden',403);\n }\n}\nadd_filter( 'rest_api_init', 'api_rest_only_for_admin_users', 99 );\n</code></pre>\n"
},
{
"answer_id": 385563,
"author": "Nikhil",
"author_id": 178840,
"author_profile": "https://wordpress.stackexchange.com/users/178840",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using a firewall to protect your wordpress website then best option is to block the api endpoint which exposes user details from firewall.</p>\n<p>Detect the url <code>https://example.com/wp-json/wp/v2/users</code> and simply block it from firewall.</p>\n<p>Edit: only block the user details specific endpoint and not the whole REST api.</p>\n"
},
{
"answer_id": 398666,
"author": "Afterglow",
"author_id": 198089,
"author_profile": "https://wordpress.stackexchange.com/users/198089",
"pm_score": 0,
"selected": false,
"text": "<p>To complete 2017 BlueSuiter's answer, here is a solution to filter users by role which makes its solution compatible with the Gutenberg editor.</p>\n<pre><code>add_filter( 'rest_endpoints', function( $endpoints ) {\n \n if(is_user_logged_in()) {\n\n $user = wp_get_current_user();\n\n $roles = array('editor', 'administrator', 'author');\n\n if( array_intersect($roles, $user->roles ) ) return $endpoints; \n\n } \n\n if ( isset( $endpoints['/wp/v2/users'] ) ) unset( $endpoints['/wp/v2/users'] );\n\n if ( isset( $endpoints['/wp/v2/users/(?P<id>[\\d]+)'] ) ) unset( $endpoints['/wp/v2/users/(?P<id>[\\d]+)'] );\n\n return $endpoints;\n \n});\n</code></pre>\n<p>The Gutenberg editor needs to query the REST API to get the author. It is therefore necessary to let pass at least all the user roles of your site that have access to a Gutenberg editor, don't forget the custom posts.</p>\n<p>On the public REST API endpoint, a 404 error is returned because is_user_logged_in will always return false.</p>\n"
}
] |
2017/01/13
|
[
"https://wordpress.stackexchange.com/questions/252328",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91550/"
] |
I have upgraded my WordPress to `4.7.1`, and after that I've tried to enumerate users through REST API, which should be fixed, but I was able to retrieve users.
```
https://mywebsite.com/wp-json/wp/v2/users
```
Output:
```
[{"id":1,"name":"admin","url":"","description":"","link":"https:\/\/mywebsite\/author\/admin\/","slug":"admin","avatar_urls":{"24": ...
```
Changelog from latest version:
>
> The REST API exposed user data for all users who had authored a post
> of a public post type. WordPress 4.7.1 limits this to only post types
> which have specified that they should be shown within the REST API.
> Reported by Krogsgard and Chris Jean.
>
>
>
After installing plugin `Disable REST API`, it seems that everything is working fine, but I don't like to use for every little thing plugin.
The output after using plugin is:
```
{"code":"rest_cannot_access","message":"Only authenticated users can access the REST API.","data":{"status":401}}
```
How can I fix this issue without using plugin, or why even after upgrading this stil exist?
**EDIT 30.9.2017**
I realized that there is a conflict between `contact 7` plugin and `Disable REST API` and that will give you `401 unauthorized` error.
When you try to send a message through `contact 7` form, it will make a request
```
wp-json/contact-form-7/v1/contact-forms/258/feedback
```
and disabling that is not a good idea.
|
This code snippet will hide the users, posts, and comments endpoint results and give 404 as the result, while the rest of the API calls keep running as they were.
**::UPDATE::**
```
add_filter('rest_endpoints', function(){
$toRemove = ['users', 'posts', 'comments'];
foreach($toRemove as $val)
{
if (isset($endpoints['/wp/v2/'.$val])) {
unset($endpoints['/wp/v2/'.$val]);
}
if(isset($endpoints['/wp/v2/'.$val.'/(?P<id>[\d]+)'])) {
unset($endpoints['/wp/v2/'.$val.'/(?P<id>[\d]+)']);
}
}
return $endpoints;
});
```
**::UPDATE::**
This snippet will remove all the default endpoints.
`<?php remove_action('rest_api_init', 'create_initial_rest_routes', 99); ?>`
|
252,369 |
<p>What are the proper filter/hooks to modify the wp-login.php?action=logout confirmation page</p>
<p><a href="https://i.stack.imgur.com/toDrN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/toDrN.png" alt="enter image description here" /></a>When you logout of your site using <strong>yoursite.com/wp-login.php?action=logout</strong> , You will go to a standard page WordPress logout page that has the following text:</p>
<blockquote>
<p>You are attempting to log out of "Your Site"</p>
<p>Do you really want to log out?</p>
</blockquote>
<p>I do not see any hooks/filters to modify it, I have checked from here: <a href="https://codex.wordpress.org/Function_Reference/wp_logout_url" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/wp_logout_url</a></p>
<p>What is the best way to edit this page?</p>
|
[
{
"answer_id": 252370,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user to a desire template and modify that template according to your needs. </p>\n\n<pre><code> <?php wp_loginout( $redirect, $echo ); ?> \n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_loginout\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_loginout</a>\nThis might helps you.</p>\n"
},
{
"answer_id": 355601,
"author": "rebduvid",
"author_id": 180509,
"author_profile": "https://wordpress.stackexchange.com/users/180509",
"pm_score": 0,
"selected": false,
"text": "<p>You can except to go to that logout page.\nOnly you need to change your logout link in your frontend.</p>\n\n<pre><code><a href=\"<?php echo wp_logout_url()?>\">logout</a>\n</code></pre>\n\n<p>this code, make the logout without confirmation window. </p>\n\n<p>But also if you really need a confirmation, you can create a \"new page\" named \"confirmation\" now, in your frontend the logout can point to \"/confirmation\" you put there your nice styles, and the link using \"wp_logout_url()\" or you can make a nice js/bootstrap confirmation event.</p>\n\n<p>I hope that was helpfull.</p>\n"
}
] |
2017/01/13
|
[
"https://wordpress.stackexchange.com/questions/252369",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60720/"
] |
What are the proper filter/hooks to modify the wp-login.php?action=logout confirmation page
[](https://i.stack.imgur.com/toDrN.png)When you logout of your site using **yoursite.com/wp-login.php?action=logout** , You will go to a standard page WordPress logout page that has the following text:
>
> You are attempting to log out of "Your Site"
>
>
> Do you really want to log out?
>
>
>
I do not see any hooks/filters to modify it, I have checked from here: <https://codex.wordpress.org/Function_Reference/wp_logout_url>
What is the best way to edit this page?
|
Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user to a desire template and modify that template according to your needs.
```
<?php wp_loginout( $redirect, $echo ); ?>
```
<https://codex.wordpress.org/Function_Reference/wp_loginout>
This might helps you.
|
252,379 |
<p>I developed a plugin which processes data following user input into a number of forms on the front end. The field types within the forms and the data input varies significantly.</p>
<p>To process the data, I hook into <code>init</code> and use the following function;</p>
<pre><code>function mh_post_actions() {
if ( isset( $_POST['mh_action'] ) ) {
do_action( 'mh_' . sanitize_text_field( $_POST['mh_action'] ), $_POST );
}
} // mh_post_actions
add_action( 'init', 'mh_post_actions' );
</code></pre>
<p>Validation and sanitizing then takes place in the resulting functions hooked into <code>mh_*</code>.</p>
<p>However, recently I took the decision to publish the plugin via the WordPress.org repo.</p>
<p>On review, my code has been rejected stating that per the guidelines, I need to validate and sanitize the data before any WordPress processing takes place.</p>
<p>That is fine, but as mentioned the data can be anything, array, int, str, url, email etc...</p>
<p>I'd like to keep the function I have as it works well for me, so wondered if there was any easier way to sanitize general $_POST data which I could add to the above function in order to meet the guidelines?</p>
|
[
{
"answer_id": 252370,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user to a desire template and modify that template according to your needs. </p>\n\n<pre><code> <?php wp_loginout( $redirect, $echo ); ?> \n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_loginout\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_loginout</a>\nThis might helps you.</p>\n"
},
{
"answer_id": 355601,
"author": "rebduvid",
"author_id": 180509,
"author_profile": "https://wordpress.stackexchange.com/users/180509",
"pm_score": 0,
"selected": false,
"text": "<p>You can except to go to that logout page.\nOnly you need to change your logout link in your frontend.</p>\n\n<pre><code><a href=\"<?php echo wp_logout_url()?>\">logout</a>\n</code></pre>\n\n<p>this code, make the logout without confirmation window. </p>\n\n<p>But also if you really need a confirmation, you can create a \"new page\" named \"confirmation\" now, in your frontend the logout can point to \"/confirmation\" you put there your nice styles, and the link using \"wp_logout_url()\" or you can make a nice js/bootstrap confirmation event.</p>\n\n<p>I hope that was helpfull.</p>\n"
}
] |
2017/01/13
|
[
"https://wordpress.stackexchange.com/questions/252379",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69112/"
] |
I developed a plugin which processes data following user input into a number of forms on the front end. The field types within the forms and the data input varies significantly.
To process the data, I hook into `init` and use the following function;
```
function mh_post_actions() {
if ( isset( $_POST['mh_action'] ) ) {
do_action( 'mh_' . sanitize_text_field( $_POST['mh_action'] ), $_POST );
}
} // mh_post_actions
add_action( 'init', 'mh_post_actions' );
```
Validation and sanitizing then takes place in the resulting functions hooked into `mh_*`.
However, recently I took the decision to publish the plugin via the WordPress.org repo.
On review, my code has been rejected stating that per the guidelines, I need to validate and sanitize the data before any WordPress processing takes place.
That is fine, but as mentioned the data can be anything, array, int, str, url, email etc...
I'd like to keep the function I have as it works well for me, so wondered if there was any easier way to sanitize general $\_POST data which I could add to the above function in order to meet the guidelines?
|
Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user to a desire template and modify that template according to your needs.
```
<?php wp_loginout( $redirect, $echo ); ?>
```
<https://codex.wordpress.org/Function_Reference/wp_loginout>
This might helps you.
|
252,419 |
<p>Is there a way to post content that does not move or remains "static" within different pages? I am trying to set a description of each of my pages on my blog to give the reader an intro about each page. Is this Possible?</p>
<p>Example:</p>
<p>This is how I would want my "Audio Stories" page to look....</p>
<p>(Page)Audio Stories
(Content) In this section you will find tales of random encounters with strangers from around the world.</p>
<p>blog post</p>
<p>blog post</p>
<p>blog post</p>
<p>etc..</p>
|
[
{
"answer_id": 252370,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user to a desire template and modify that template according to your needs. </p>\n\n<pre><code> <?php wp_loginout( $redirect, $echo ); ?> \n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_loginout\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_loginout</a>\nThis might helps you.</p>\n"
},
{
"answer_id": 355601,
"author": "rebduvid",
"author_id": 180509,
"author_profile": "https://wordpress.stackexchange.com/users/180509",
"pm_score": 0,
"selected": false,
"text": "<p>You can except to go to that logout page.\nOnly you need to change your logout link in your frontend.</p>\n\n<pre><code><a href=\"<?php echo wp_logout_url()?>\">logout</a>\n</code></pre>\n\n<p>this code, make the logout without confirmation window. </p>\n\n<p>But also if you really need a confirmation, you can create a \"new page\" named \"confirmation\" now, in your frontend the logout can point to \"/confirmation\" you put there your nice styles, and the link using \"wp_logout_url()\" or you can make a nice js/bootstrap confirmation event.</p>\n\n<p>I hope that was helpfull.</p>\n"
}
] |
2017/01/13
|
[
"https://wordpress.stackexchange.com/questions/252419",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110866/"
] |
Is there a way to post content that does not move or remains "static" within different pages? I am trying to set a description of each of my pages on my blog to give the reader an intro about each page. Is this Possible?
Example:
This is how I would want my "Audio Stories" page to look....
(Page)Audio Stories
(Content) In this section you will find tales of random encounters with strangers from around the world.
blog post
blog post
blog post
etc..
|
Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user to a desire template and modify that template according to your needs.
```
<?php wp_loginout( $redirect, $echo ); ?>
```
<https://codex.wordpress.org/Function_Reference/wp_loginout>
This might helps you.
|
252,426 |
<p><strong>TLDR</strong>: While in the backend, I would like to add custom post type inside a menu page (which I can do). But I cannot order the resulting submenu pages.</p>
<hr>
<p>I have <strong>3 custom post types</strong> “A”, “B”, “C”, and I want to:</p>
<ol>
<li><strong>Group</strong> the 3 contents <strong>under one menu page</strong> called “My Custom Page”</li>
<li>When I click “My Custom Page”, being <strong>redirected to the content</strong> of “My Custom Page”, and <strong>not one of the custom post types</strong>.</li>
</ol>
<p>I accomplished the first half quite easilly: I created a menu pages as follows:</p>
<pre><code>add_menu_page('My Custom Page', 'My Custom Page', 'manage_options', 'my-top-level-slug');
</code></pre>
<p>And then, I set each custom post type like this:</p>
<pre><code>'show_in_menu'=> 'my-top-level-slug'
</code></pre>
<p>This allows me to successfully group my 3 custom post types under one single menu page. And <strong>here lies the problem</strong>: if I click on “My Custom Page”, I get redirected to the first custom post type (depending on the inclusion order) – I would like to click on “My Custom Page” and get redirected to said page (where I plan on list show stats, most viewed posts, etc), but instead a custom post type opens up, which I don’t really want.</p>
<p>I figured I could add a submenu page, but any submenu page I add gets included AFTER the custom post types (so at the bottom of the submenu pages list). So I’m wondering if is there a way to assign an order to those subpages, so that if I click over “My Custom Page”, it’s not gonna show a custom post type.</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>After some searching, I found the following article on the Codex: <a href="https://developer.wordpress.org/reference/functions/add_submenu_page/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/functions/add_submenu_page/</a> . By following this example and embeding this code:</p>
<pre><code>function wpdocs_register_my_custom_submenu_page() {
add_submenu_page(
'my-menu',
'My Custom Submenu Page',
'My Custom Submenu Page',
'manage_options',
'edit.php?post_type=CPT-NAME',
false
);
}
add_action('admin_menu', 'wpdocs_register_my_custom_submenu_page');
</code></pre>
<p>I'm able to accomplish the 2 points above (so the grouping works and when I click I get redirected to a review page). But - by doing so, once I enter inside a post (create or edit one, doesn't matter) the <strong>menu page does't result active</strong> anymore: if I hover on the menu page, it's marked in white as in active, but otherwise the menu & submenus are collapsed/closed.</p>
<p>The previous solution was working correctly (menu state wise), but didn't allow me to assign a custom page to “My Custom Page”. As for the second solution, it's vice versa (menu state is inactive while inside a post, but I can show “My Custom Page”).</p>
|
[
{
"answer_id": 252428,
"author": "Cerere",
"author_id": 16281,
"author_profile": "https://wordpress.stackexchange.com/users/16281",
"pm_score": 3,
"selected": true,
"text": "<p>I found the answer. To make it short:</p>\n<h1>SOLUTION 1</h1>\n<p>If you want to simply add a custom post type to a menu item, go with solution number one (which involves creating a menu page with <code>add_menu_page</code>and setting <code>'show_in_menu=>'</code> to your menu page slug). It works, but if you click on your newly created menu page, you will get redirected to the first CPT (any subpage will get pushed at the end of the list).</p>\n<h1>SOLUTION 2</h1>\n<p>If you want to group you custom post types, click on your menu page and end up on a subpage, then go with solution number 2 (see update above): set <code>'show_in_menu=> false'</code>, then create a function like this:</p>\n<pre><code>function create_menupages_252428() {\n\n// https://developer.wordpress.org/reference/functions/add_menu_page/\n\nadd_menu_page(\n 'Page', // Page title\n 'Page', // Menu title\n 'manage_options', // Capability\n 'page', // Slug\n 'mycustompage', // Function name\n 'dashicons-format-aside', // Slug\n 1 // Order\n);\n\n// https://developer.wordpress.org/reference/functions/add_submenu_page/\n\nadd_submenu_page(\n 'page', // Parent slug\n 'subpage', // Page title\n 'subpage', // Menu title\n 'manage_options', // Capability\n 'edit.php?post_type=CPT', // Slug\n false // Function\n);\n}\nadd_action('admin_menu', 'create_menupages_252428');\n</code></pre>\n<p>Once done, if you want to show the menu page as active while operating on your custom post type,</p>\n<pre><code>function menu_active_252428() {\nglobal $parent_file, $post_type;\nif ( $post_type == 'CPT' ) {\n $parent_file = 'page';\n}\n}\nadd_action( 'admin_head', 'menu_active_252428' );\n</code></pre>\n<p>If by any chance you find a better way, feel free to add/correct my solution!</p>\n"
},
{
"answer_id": 336641,
"author": "Rodrigo García",
"author_id": 167035,
"author_profile": "https://wordpress.stackexchange.com/users/167035",
"pm_score": 0,
"selected": false,
"text": "<p>Update: \nNow you just need to create the menu page with:</p>\n\n<pre><code>function create_home_menu(){\n add_menu_page(\n 'Página de Inicio',\n 'Inicio/Home',\n 'manage_options',\n 'my_home_menu',\n 'mycustompage',\n 'dashicons-admin-home',\n 2\n );\n}\nadd_action('admin_menu', 'create_home_menu');\n</code></pre>\n\n<p>And then be sure that when you create a post type add <code>'show_ui'=>true</code> and <code>'show_in_menu'=>'my_home_menu'</code> where 'my_home_menu is the slug you gave to the menu created before.</p>\n\n<p>Show UI makes it visible to edit and change, and show in menu adds it to the menu as submenu by default. Now you don't need to add extra function to make the parent menu appear as selected when editing the post type.</p>\n"
},
{
"answer_id": 411326,
"author": "ApsaraAruna",
"author_id": 105670,
"author_profile": "https://wordpress.stackexchange.com/users/105670",
"pm_score": 0,
"selected": false,
"text": "<p>@cerere ,\nTo be active in the submenu only need <code>'show_in_menu' => false</code> in the argument.</p>\n<p>no need to add this function.</p>\n<pre><code>function menu_active_252428() {\n global $parent_file, $post_type;\n if ( $post_type == 'CPT' ) {\n $parent_file = 'page';\n }\n}\nadd_action( 'admin_head', 'menu_active_252428' );\n</code></pre>\n<h1>Menu</h1>\n<pre><code>add_menu_page(\n 'Main menu', // The title to be displayed in the browser window for this page.\n 'Main menu', // The text to be displayed for this menu item\n 'manage_options', // Which type of users can see this menu item\n 'plugin_demo_options', // The unique ID - that is, the slug - for this menu item\n array($this, 'call_back_function') // The name of the function to call when rendering this menu's page\n );\n\n add_submenu_page('plugin_demo_options', 'Submenu Page Title', 'Whatever You Want', 'manage_options', 'my-menu', 'acutions_customers_spendings_list');\n add_submenu_page('plugin_demo_options', 'Test Settings', 'Test Settings', 'manage_options', 'edit.php?post_type=books', false);\n</code></pre>\n<h1>Custom Post type</h1>\n<pre><code> /*Custom Post type start*/\nfunction post_type_book()\n{\n $supports = array(\n 'title', // post title\n 'author', // post author\n 'thumbnail', // featured images\n 'excerpt', // post excerpt\n 'custom-fields', // custom fields\n 'comments', // post comments\n 'revisions', // post revisions\n 'post-formats', // post formats\n );\n $labels = array(\n 'name' => _x('Books', 'plural'),\n 'singular_name' => _x('Book', 'singular'),\n 'menu_name' => _x('Books', 'admin menu'),\n 'name_admin_bar' => _x('Books', 'admin bar'),\n 'add_new' => _x('Add Book', 'add new'),\n 'add_new_item' => __('Add New Book'),\n 'new_item' => __('New Book'),\n 'edit_item' => __('Edit Book'),\n 'view_item' => __('View Book'),\n 'all_items' => __('All Book'),\n 'search_items' => __('Search Book'),\n 'not_found' => __('No Bookfound.'),\n );\n $args = array(\n 'taxonomies' => array(''),\n 'supports' => $supports,\n 'labels' => $labels,\n 'public' => true,\n 'show_in_menu' => false,\n 'show_in_nav_menus' => false,\n 'show_in_admin_bar' => false,\n 'query_var' => true,\n 'rewrite' => array('slug' => 'books', 'with_front' => false, 'pages' => true, 'feeds' => true,),\n 'has_archive' => false,\n 'hierarchical' => false,\n );\n register_taxonomy(\n 'book-category',\n array('books'),\n array(\n 'hierarchical' => true,\n 'label' => 'Categories',\n 'singular_label' => 'Category',\n 'rewrite' => array('slug' => 'book-category')\n )\n );\n register_post_type('books', $args);\n}\n</code></pre>\n<h1>Screenshot</h1>\n<p><a href=\"https://i.stack.imgur.com/IVT4d.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IVT4d.png\" alt=\"enter image description here\" /></a></p>\n"
}
] |
2017/01/13
|
[
"https://wordpress.stackexchange.com/questions/252426",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16281/"
] |
**TLDR**: While in the backend, I would like to add custom post type inside a menu page (which I can do). But I cannot order the resulting submenu pages.
---
I have **3 custom post types** “A”, “B”, “C”, and I want to:
1. **Group** the 3 contents **under one menu page** called “My Custom Page”
2. When I click “My Custom Page”, being **redirected to the content** of “My Custom Page”, and **not one of the custom post types**.
I accomplished the first half quite easilly: I created a menu pages as follows:
```
add_menu_page('My Custom Page', 'My Custom Page', 'manage_options', 'my-top-level-slug');
```
And then, I set each custom post type like this:
```
'show_in_menu'=> 'my-top-level-slug'
```
This allows me to successfully group my 3 custom post types under one single menu page. And **here lies the problem**: if I click on “My Custom Page”, I get redirected to the first custom post type (depending on the inclusion order) – I would like to click on “My Custom Page” and get redirected to said page (where I plan on list show stats, most viewed posts, etc), but instead a custom post type opens up, which I don’t really want.
I figured I could add a submenu page, but any submenu page I add gets included AFTER the custom post types (so at the bottom of the submenu pages list). So I’m wondering if is there a way to assign an order to those subpages, so that if I click over “My Custom Page”, it’s not gonna show a custom post type.
---
**UPDATE**
After some searching, I found the following article on the Codex: <https://developer.wordpress.org/reference/functions/add_submenu_page/> . By following this example and embeding this code:
```
function wpdocs_register_my_custom_submenu_page() {
add_submenu_page(
'my-menu',
'My Custom Submenu Page',
'My Custom Submenu Page',
'manage_options',
'edit.php?post_type=CPT-NAME',
false
);
}
add_action('admin_menu', 'wpdocs_register_my_custom_submenu_page');
```
I'm able to accomplish the 2 points above (so the grouping works and when I click I get redirected to a review page). But - by doing so, once I enter inside a post (create or edit one, doesn't matter) the **menu page does't result active** anymore: if I hover on the menu page, it's marked in white as in active, but otherwise the menu & submenus are collapsed/closed.
The previous solution was working correctly (menu state wise), but didn't allow me to assign a custom page to “My Custom Page”. As for the second solution, it's vice versa (menu state is inactive while inside a post, but I can show “My Custom Page”).
|
I found the answer. To make it short:
SOLUTION 1
==========
If you want to simply add a custom post type to a menu item, go with solution number one (which involves creating a menu page with `add_menu_page`and setting `'show_in_menu=>'` to your menu page slug). It works, but if you click on your newly created menu page, you will get redirected to the first CPT (any subpage will get pushed at the end of the list).
SOLUTION 2
==========
If you want to group you custom post types, click on your menu page and end up on a subpage, then go with solution number 2 (see update above): set `'show_in_menu=> false'`, then create a function like this:
```
function create_menupages_252428() {
// https://developer.wordpress.org/reference/functions/add_menu_page/
add_menu_page(
'Page', // Page title
'Page', // Menu title
'manage_options', // Capability
'page', // Slug
'mycustompage', // Function name
'dashicons-format-aside', // Slug
1 // Order
);
// https://developer.wordpress.org/reference/functions/add_submenu_page/
add_submenu_page(
'page', // Parent slug
'subpage', // Page title
'subpage', // Menu title
'manage_options', // Capability
'edit.php?post_type=CPT', // Slug
false // Function
);
}
add_action('admin_menu', 'create_menupages_252428');
```
Once done, if you want to show the menu page as active while operating on your custom post type,
```
function menu_active_252428() {
global $parent_file, $post_type;
if ( $post_type == 'CPT' ) {
$parent_file = 'page';
}
}
add_action( 'admin_head', 'menu_active_252428' );
```
If by any chance you find a better way, feel free to add/correct my solution!
|
252,431 |
<p>I'm hooking into <code>the_editor_content</code> to add a signature to new posts. However, when a user edits their post the content is lost and replaced with the signature. </p>
<p>I tried something like the following in the hopes that the <code>the_editor_content</code> would only fire for new posts: </p>
<pre><code>add_action( 'new_to_publish', 'my_new_post');
function my_new_post( $post ) {
function my_editor_content( $content ) {
$current_user = wp_get_current_user();
$author_name = $current_user->display_name;
$editor_content = '<br><br><br><br><br>--<br>'.$author_name;
return $editor_content;
}
add_filter( 'the_editor_content', 'my_editor_content', 'tinymce' );
}
</code></pre>
<p>But it isn't working, I don't get the signature for new posts or any posts. Can this even be done this way? Note that <code>my_editor_content</code> works fine by itself.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 252445,
"author": "Mike",
"author_id": 69112,
"author_profile": "https://wordpress.stackexchange.com/users/69112",
"pm_score": 1,
"selected": false,
"text": "<p>OK, so the <code>new_to_publish</code> hook is probably not the right hook to use here.</p>\n\n<p>The <code>status_to_status</code> hooks run during a posts transition from the first status to the second. By this stage, the editor is no longer in play.</p>\n\n<p>If my understanding of <code>the_editor_content</code> is correct, this filters the default content displayed in the editor when the post edit screen is loaded.</p>\n\n<p>Do you need the signature to be appended to the actual post content within the database or just to display the on the front end?</p>\n\n<p>If the latter, you could use the <code>the_content</code> filter...</p>\n\n<pre><code>function mh_add_signature_after_content( $content ) {\n global $post;\n\n $signature = '';\n\n // Specify the post type on which to display, otherwise you'll see on pages also!\n if ( 'post' == $post->post_type ) {\n\n $author_name = get_the_author_meta( 'display_name', 25 );\n\n $signature = '<br><br><br><br><br>--<br>' . $author_name;\n\n }\n\n return $content . $signature;\n} // kbs_after_article_content\nadd_filter( 'the_content', 'mh_add_signature_after_content', 999 );\n</code></pre>\n\n<p>The result of this would be that in the post edit screen, the editor will display the post content, no signature. But when loaded on the front end of your site, the post will include the signature.</p>\n\n<p><strong>UPDATED</strong></p>\n\n<p>This should achieve what you want...</p>\n\n<pre><code>add_action( 'save_post', 'my_new_post');\nfunction my_new_post( $post_id ) {\n\n // Specify the post type on which to run\n if ( 'post' == $post->post_type ) {\n\n // Prevent loops\n remove_action( 'save_post', 'my_new_post' );\n\n // Make sure we haven't already run for this post\n if ( get_post_meta( $post_id, 'signature_added', true ) ) {\n return;\n }\n\n $signature = '';\n $post = get_post( $post_id );\n\n $author_name = get_the_author_meta( 'display_name', $post_id );\n\n $signature = '<br><br><br><br><br>--<br>' . $author_name;\n\n $update = wp_update_post( array(\n 'ID' => $post_id,\n 'post_content' => $post->post_content . $signature\n ) );\n\n // Add a placeholder so we know the signature was added\n if ( ! is_wp_error( $update ) ) {\n add_post_meta( $post_id, 'signature_added', true, true );\n }\n\n add_action( 'save_post', 'my_new_post' );\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 252626,
"author": "jetgo",
"author_id": 98236,
"author_profile": "https://wordpress.stackexchange.com/users/98236",
"pm_score": -1,
"selected": true,
"text": "<p>I went with a different approach to solve this (probably not the cleanest one but it works for me).</p>\n\n<p>I parsed the current url and added the signature with <code>the_editor_content</code> if on the page for new posts. </p>\n\n<p>If on the page for editing posts, I parsed the url again to get the post id and return the post content in the editor. </p>\n\n<p>I have frontend posting forms so it works. </p>\n"
}
] |
2017/01/13
|
[
"https://wordpress.stackexchange.com/questions/252431",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98236/"
] |
I'm hooking into `the_editor_content` to add a signature to new posts. However, when a user edits their post the content is lost and replaced with the signature.
I tried something like the following in the hopes that the `the_editor_content` would only fire for new posts:
```
add_action( 'new_to_publish', 'my_new_post');
function my_new_post( $post ) {
function my_editor_content( $content ) {
$current_user = wp_get_current_user();
$author_name = $current_user->display_name;
$editor_content = '<br><br><br><br><br>--<br>'.$author_name;
return $editor_content;
}
add_filter( 'the_editor_content', 'my_editor_content', 'tinymce' );
}
```
But it isn't working, I don't get the signature for new posts or any posts. Can this even be done this way? Note that `my_editor_content` works fine by itself.
Thanks in advance.
|
I went with a different approach to solve this (probably not the cleanest one but it works for me).
I parsed the current url and added the signature with `the_editor_content` if on the page for new posts.
If on the page for editing posts, I parsed the url again to get the post id and return the post content in the editor.
I have frontend posting forms so it works.
|
252,458 |
<p>Trying to create a 'switching' blog template using home.php, controlled by 'Blog posts per page' setting in the admin area. If set to '1', it will show the single post template. Anything higher and it will display the archive template.</p>
<p><strong>In detail:</strong></p>
<p>The following code works, except for archive pagination (clicking older/newer posts changes the URL but displays first page content only).</p>
<pre><code><div id="primary" class="content-area">
<h2>Switching Blog Template</h2>
<?php // Get ppp for query
$ppp_val = get_option( 'posts_per_page' ); ?>
<?php
// Single post loop
$blogsingle_query = new WP_Query( $ppp_val <= 1 );
if($blogsingle_query->have_posts()) :
while($blogsingle_query->have_posts()) : $blogsingle_query->the_post();
get_template_part( 'parts/content', 'post' );
endwhile;
wp_reset_postdata();
the_post_navigation();
endif;
?>
<?php
// Multiple posts loop ( PAGINATION DOESN'T WORK )
$blogmulti_query = new WP_Query( $ppp_val > 1 );
if($blogmulti_query->have_posts()) :
while($blogmulti_query->have_posts()) : $blogmulti_query->the_post();
get_template_part( 'parts/content', 'archive' );
endwhile;
wp_reset_postdata();
the_posts_navigation();
endif;
?>
</div><!-- #primary -->
</code></pre>
<p>In comparison, this alternate method does not work but feels like it might be a better track to follow?</p>
<pre><code><div id="primary" class="content-area">
<h2>Switching Blog Template</h2>
<?php $ppp_val = get_option( 'posts_per_page' ); ?>
<?php
$args=array(
'posts_per_page' => $ppp_val, // Get number of posts value
'meta_query' = array(
array(
'key' => 'posts_per_page', // Use this to compare
'compare' => '>',
'value' => 1,
'type' => 'NUMERIC',
)
),
);
$switch_query = new WP_Query( $args );
?>
<?php
if($switch_query->have_posts()) :
while($switch_query->have_posts()) : $switch_query->the_post();
get_template_part( 'parts/content', 'archive' );
endwhile; else:
?>
<?php get_template_part( 'parts/content', 'post' ); ?>
<?php endif; ?>
</div><!-- #primary -->
</code></pre>
|
[
{
"answer_id": 252459,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>You can control what template loads for any type of query via the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#filter-hierarchy\" rel=\"nofollow noreferrer\">Template Filters</a>.</p>\n\n<p>Here's an example using <code>home_template</code> that checks if <code>posts_per_page</code> is equal to <code>1</code>, and loads <code>single.php</code> in that case.</p>\n\n<pre><code>function wpd_home_template( $home_template = '' ){\n if( get_option( 'posts_per_page' ) == 1 ){\n $home_template = locate_template( 'single.php', false );\n }\n return $home_template;\n}\nadd_filter( 'home_template', 'wpd_home_template' );\n</code></pre>\n"
},
{
"answer_id": 252460,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to Milo, whose answer was perfect. I hadn't encountered Template Filters before.</p>\n\n<p>For the benefit of future readers, my final code (below) has been amended to reference both templates required.</p>\n\n<pre><code>function wpd_home_template( $home_template = '' ){\n if( get_option( 'posts_per_page' ) == 1 ){\n $home_template = locate_template( 'single.php', false );\n }\n elseif( get_option( 'posts_per_page' ) > 1 ){\n $home_template = locate_template( 'archive.php', false );\n }\n return $home_template;\n}\nadd_filter( 'home_template', 'wpd_home_template' );\n</code></pre>\n\n<p>Over and out! </p>\n\n<p><strong>-A</strong></p>\n"
}
] |
2017/01/14
|
[
"https://wordpress.stackexchange.com/questions/252458",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
Trying to create a 'switching' blog template using home.php, controlled by 'Blog posts per page' setting in the admin area. If set to '1', it will show the single post template. Anything higher and it will display the archive template.
**In detail:**
The following code works, except for archive pagination (clicking older/newer posts changes the URL but displays first page content only).
```
<div id="primary" class="content-area">
<h2>Switching Blog Template</h2>
<?php // Get ppp for query
$ppp_val = get_option( 'posts_per_page' ); ?>
<?php
// Single post loop
$blogsingle_query = new WP_Query( $ppp_val <= 1 );
if($blogsingle_query->have_posts()) :
while($blogsingle_query->have_posts()) : $blogsingle_query->the_post();
get_template_part( 'parts/content', 'post' );
endwhile;
wp_reset_postdata();
the_post_navigation();
endif;
?>
<?php
// Multiple posts loop ( PAGINATION DOESN'T WORK )
$blogmulti_query = new WP_Query( $ppp_val > 1 );
if($blogmulti_query->have_posts()) :
while($blogmulti_query->have_posts()) : $blogmulti_query->the_post();
get_template_part( 'parts/content', 'archive' );
endwhile;
wp_reset_postdata();
the_posts_navigation();
endif;
?>
</div><!-- #primary -->
```
In comparison, this alternate method does not work but feels like it might be a better track to follow?
```
<div id="primary" class="content-area">
<h2>Switching Blog Template</h2>
<?php $ppp_val = get_option( 'posts_per_page' ); ?>
<?php
$args=array(
'posts_per_page' => $ppp_val, // Get number of posts value
'meta_query' = array(
array(
'key' => 'posts_per_page', // Use this to compare
'compare' => '>',
'value' => 1,
'type' => 'NUMERIC',
)
),
);
$switch_query = new WP_Query( $args );
?>
<?php
if($switch_query->have_posts()) :
while($switch_query->have_posts()) : $switch_query->the_post();
get_template_part( 'parts/content', 'archive' );
endwhile; else:
?>
<?php get_template_part( 'parts/content', 'post' ); ?>
<?php endif; ?>
</div><!-- #primary -->
```
|
You can control what template loads for any type of query via the [Template Filters](https://developer.wordpress.org/themes/basics/template-hierarchy/#filter-hierarchy).
Here's an example using `home_template` that checks if `posts_per_page` is equal to `1`, and loads `single.php` in that case.
```
function wpd_home_template( $home_template = '' ){
if( get_option( 'posts_per_page' ) == 1 ){
$home_template = locate_template( 'single.php', false );
}
return $home_template;
}
add_filter( 'home_template', 'wpd_home_template' );
```
|
252,532 |
<p>After upgrading to php 5.6.4 my widgets file causes:</p>
<p><code>Parse error: syntax error, unexpected 'class' (T_CLASS) in /home/path/fss-widgets.php on line 1</code></p>
<p>I'm mystified - several hours research has yielded nothing. The problem doesn't appear to be quoting, escaping, or anything else you would expect in this situation and the code looks ok to me.</p>
<pre><code><?php
/*
Plugin Name: FSS Vacancy Widget
Plugin URI: http://www.url.com/
Description: Shows recent vacancies
Author: Name
Version: 1.0
Author URI: http://www.url.com/
*/
class FSSVacancyWidget extends WP_Widget
{
function FSSVacancyWidget()
{
$widget_ops = array('classname' => 'FSSVacancyWidget', 'description' => 'Displays Recent FSS Jobs on the homepage and all other pages' );
$this->WP_Widget('FSSVacancyWidget', 'FSS Vacancies', $widget_ops);
}
function form($instance)
{
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = $instance['title'];
$fss_numposts = $instance['fss_numposts'];
$fss_vacurl = $instance['fss_vacurl'];
$fss_morevac = $instance['fss_morevac'];
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_numposts'); ?>">Number of Posts (Default is 10): <input class="widefat" id="<?php echo $this->get_field_id('fss_numposts'); ?>" name="<?php echo $this->get_field_name('fss_numposts'); ?>" type="text" value="<?php echo attribute_escape($fss_numposts); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_vacurl'); ?>">Vacancy URL: <input class="widefat" id="<?php echo $this->get_field_id('fss_vacurl'); ?>" name="<?php echo $this->get_field_name('fss_vacurl'); ?>" type="text" value="<?php echo attribute_escape($fss_vacurl); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_morevac'); ?>">More Vacancies Title: <input class="widefat" id="<?php echo $this->get_field_id('fss_morevac'); ?>" name="<?php echo $this->get_field_name('fss_morevac'); ?>" type="text" value="<?php echo attribute_escape($fss_morevac); ?>" /></label></p>
<?php
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
$instance['fss_numposts'] = $new_instance['fss_numposts'];
$instance['fss_vacurl'] = $new_instance['fss_vacurl'];
$instance['fss_morevac'] = $new_instance['fss_morevac'];
return $instance;
}
function widget($args, $instance)
{
extract($args, EXTR_SKIP);
/* User-selected settings. */
$fss_numposts = $instance['fss_numposts'];
$fss_vacurl = $instance['fss_vacurl'];
$fss_morevac = $instance['fss_morevac'];
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
if (!empty($title))
echo $before_title . $title . $after_title;;
echo "<ul class='items'>";
query_posts( array( 'showposts' => $fss_numposts ) );
if ( have_posts() ) : while ( have_posts() ) : the_post();
echo "<li><a href='".get_permalink()."'><span class='job-title'>".get_the_title()."</span><span class='job-date'>".get_the_date('d m Y')."</span></a></li>";
endwhile; endif; wp_reset_query();
echo "</ul>";
echo"<a href='".$fss_vacurl."' class='view'>".$fss_morevac."</a>";
echo $after_widget;
}
}
add_action( 'widgets_init', create_function('', 'return register_widget("FSSVacancyWidget");') );
</code></pre>
|
[
{
"answer_id": 252577,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 4,
"selected": true,
"text": "<p>An error about something on <strong>line 1</strong> that is actually on a later position means that PHP doesn't recognize your line endings. </p>\n\n<p>There are three ways to encode a line ending, and PHP understands only two of them:</p>\n\n<ol>\n<li>LF, or <code>\\n</code>, Line Feed, <a href=\"http://www.fileformat.info/info/unicode/char/000A/index.htm\">U+000A</a></li>\n<li>CR, or <code>\\r</code>, Carriage Return, <a href=\"http://www.fileformat.info/info/unicode/char/000D/index.htm\">U+000D</a></li>\n<li>CRLF, or <code>\\r\\n</code>, the combination of the first and the second</li>\n</ol>\n\n<p>LF is the default on systems like UNIX, Linux, and Mac OS X (since 2001).<br>\nCRLF is the default in Windows, inherited from <a href=\"https://en.wikipedia.org/wiki/CP/M\">CP/M</a>. Just LF works on Windows too nowadays, there is no need to use CRLF anymore.<br>\nCR was the default in <a href=\"https://en.wikipedia.org/wiki/Classic_Mac_OS\">Classic Mac OS</a> until 2001.</p>\n\n<p>PHP doesn't understand 2., CR only, which is understandable, because no one is using that anymore. Well, almost no one. There are still some editors out there that not only allow that obsolete line ending encoding, they don't even warn their users when they are using it.</p>\n\n<p>Set your editor to use LF only, and you are safe. Unfortunately, the <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/\">WordPress Coding Standards</a> are silent about this.</p>\n"
},
{
"answer_id": 252613,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>@tosho's answer is too good.</p>\n<p>What just happened is PHP parsers tries to parse that file and creates <a href=\"http://php.net/manual/en/tokens.php\" rel=\"nofollow noreferrer\">tokens</a> first, and gets confused with the first token <code>class</code>, becuase the parser for that version of PHP cannot work well with <code>\\r</code> characters.</p>\n<p>Happens that also other invisible Unicode characters may break the parser.\nThe main thing you just cannot understand the problem from the editor unless you open Hex editor.</p>\n<p>BOM character also (props @MarkKaplun) can make problems.\nThere are some Unicode n-dash characters that may look just like <code>-</code> (minus), and you can scratch your head for days.</p>\n<p>In this case, as you confirmed <code>\\r</code> <strong>carriage return character</strong> was your problem.</p>\n<p>But this is dependent on PHP version. I tested your code on PHP 7 and no problem found.</p>\n<p>I noticed that WPSO editor will trim the <code>\\r</code> character, and I added it manually when tested.</p>\n<p><a href=\"https://i.stack.imgur.com/QNnRu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QNnRu.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.stack.imgur.com/5nKNV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5nKNV.png\" alt=\"enter image description here\" /></a></p>\n<p>The moral of the story.</p>\n<h3>Fix the line endings from your editor, for your project via regex replace.</h3>\n<p>But also fix endings for non-PHP files.</p>\n<pre><code>define('CR', "\\r"); // Carriage Return: Classic Mac\ndefine('CRLF', "\\r\\n"); // Carriage Return and Line Feed: Windows\ndefine('LF', "\\n"); // Best: Unix, Linux, Mac, Windows\n\n\nfunction fix_endings($s) {\n // Convert all line-endings to the Best format.\n $s = str_replace( CRLF, LF, $s );\n $s = str_replace( CR, LF, $s );\n // Don't allow out-of-control blank lines\n $s = preg_replace( "/\\n{2,}/", LF . LF, $s );\n return $s;\n}\n</code></pre>\n<p><em>The line endings are very important and may also have security implications. If the PHP parser fails on some characters you may guess some PHP functions that read files may also.</em></p>\n"
}
] |
2017/01/14
|
[
"https://wordpress.stackexchange.com/questions/252532",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3782/"
] |
After upgrading to php 5.6.4 my widgets file causes:
`Parse error: syntax error, unexpected 'class' (T_CLASS) in /home/path/fss-widgets.php on line 1`
I'm mystified - several hours research has yielded nothing. The problem doesn't appear to be quoting, escaping, or anything else you would expect in this situation and the code looks ok to me.
```
<?php
/*
Plugin Name: FSS Vacancy Widget
Plugin URI: http://www.url.com/
Description: Shows recent vacancies
Author: Name
Version: 1.0
Author URI: http://www.url.com/
*/
class FSSVacancyWidget extends WP_Widget
{
function FSSVacancyWidget()
{
$widget_ops = array('classname' => 'FSSVacancyWidget', 'description' => 'Displays Recent FSS Jobs on the homepage and all other pages' );
$this->WP_Widget('FSSVacancyWidget', 'FSS Vacancies', $widget_ops);
}
function form($instance)
{
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = $instance['title'];
$fss_numposts = $instance['fss_numposts'];
$fss_vacurl = $instance['fss_vacurl'];
$fss_morevac = $instance['fss_morevac'];
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_numposts'); ?>">Number of Posts (Default is 10): <input class="widefat" id="<?php echo $this->get_field_id('fss_numposts'); ?>" name="<?php echo $this->get_field_name('fss_numposts'); ?>" type="text" value="<?php echo attribute_escape($fss_numposts); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_vacurl'); ?>">Vacancy URL: <input class="widefat" id="<?php echo $this->get_field_id('fss_vacurl'); ?>" name="<?php echo $this->get_field_name('fss_vacurl'); ?>" type="text" value="<?php echo attribute_escape($fss_vacurl); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_morevac'); ?>">More Vacancies Title: <input class="widefat" id="<?php echo $this->get_field_id('fss_morevac'); ?>" name="<?php echo $this->get_field_name('fss_morevac'); ?>" type="text" value="<?php echo attribute_escape($fss_morevac); ?>" /></label></p>
<?php
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
$instance['fss_numposts'] = $new_instance['fss_numposts'];
$instance['fss_vacurl'] = $new_instance['fss_vacurl'];
$instance['fss_morevac'] = $new_instance['fss_morevac'];
return $instance;
}
function widget($args, $instance)
{
extract($args, EXTR_SKIP);
/* User-selected settings. */
$fss_numposts = $instance['fss_numposts'];
$fss_vacurl = $instance['fss_vacurl'];
$fss_morevac = $instance['fss_morevac'];
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
if (!empty($title))
echo $before_title . $title . $after_title;;
echo "<ul class='items'>";
query_posts( array( 'showposts' => $fss_numposts ) );
if ( have_posts() ) : while ( have_posts() ) : the_post();
echo "<li><a href='".get_permalink()."'><span class='job-title'>".get_the_title()."</span><span class='job-date'>".get_the_date('d m Y')."</span></a></li>";
endwhile; endif; wp_reset_query();
echo "</ul>";
echo"<a href='".$fss_vacurl."' class='view'>".$fss_morevac."</a>";
echo $after_widget;
}
}
add_action( 'widgets_init', create_function('', 'return register_widget("FSSVacancyWidget");') );
```
|
An error about something on **line 1** that is actually on a later position means that PHP doesn't recognize your line endings.
There are three ways to encode a line ending, and PHP understands only two of them:
1. LF, or `\n`, Line Feed, [U+000A](http://www.fileformat.info/info/unicode/char/000A/index.htm)
2. CR, or `\r`, Carriage Return, [U+000D](http://www.fileformat.info/info/unicode/char/000D/index.htm)
3. CRLF, or `\r\n`, the combination of the first and the second
LF is the default on systems like UNIX, Linux, and Mac OS X (since 2001).
CRLF is the default in Windows, inherited from [CP/M](https://en.wikipedia.org/wiki/CP/M). Just LF works on Windows too nowadays, there is no need to use CRLF anymore.
CR was the default in [Classic Mac OS](https://en.wikipedia.org/wiki/Classic_Mac_OS) until 2001.
PHP doesn't understand 2., CR only, which is understandable, because no one is using that anymore. Well, almost no one. There are still some editors out there that not only allow that obsolete line ending encoding, they don't even warn their users when they are using it.
Set your editor to use LF only, and you are safe. Unfortunately, the [WordPress Coding Standards](https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/) are silent about this.
|
252,559 |
<p>I have image file stored inside theme directory called site.</p>
<p>Now in my home page using wordpress page editor I have put the following code but it didn't display image, seems location is wrong.</p>
<pre><code><img src="site/images/footLogo.png" style="padding: 0px!important; color:white">
</code></pre>
<p>let me know what issue?</p>
|
[
{
"answer_id": 252561,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": 1,
"selected": false,
"text": "<p>You'll have to copy the full path to the image like so:<br>\n<code>http://www.your-site-name.extension/wp-content/themes/site/images/footLogo.png</code> in your <code><img src=\"\"></code>.</p>\n\n<p>WordPress works with absolute urls.</p>\n"
},
{
"answer_id": 252563,
"author": "Muhammad Muazzam",
"author_id": 95126,
"author_profile": "https://wordpress.stackexchange.com/users/95126",
"pm_score": 2,
"selected": true,
"text": "<p>You can define constant in theme function file as:</p>\n\n<pre><code>if( !defined(THEME_IMG_PATH)){\n define( 'THEME_IMG_PATH', get_stylesheet_directory_uri() . '/site/images' );\n }\n</code></pre>\n\n<p>and then you can use img tag as</p>\n\n<pre><code> <img src=\"<?php echo THEME_IMG_PATH; ?>/footLogo.png\" style=\"padding: 0px!important; color:white\">\n</code></pre>\n"
},
{
"answer_id": 252572,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<h2>Absolute URLs</h2>\n\n<p>As other have said, you need to use the full URL for your image <code>src</code> attribute, or the browser will not be able to find it.</p>\n\n<p>WordPress provides the function <code>get_template_directory_uri()</code> that returns the full URL to your theme path.</p>\n\n<p>So, by doing:</p>\n\n<pre><code><?php\n$img_src = get_template_directory_uri() . '/site/images/footLogo.png';\n?>\n\n<img src=\"<?php echo $img_src ?>\" style=\"padding: 0px!important; color:white\">\n</code></pre>\n\n<p>your image will be shown, assuming the path is correct and the file is there.</p>\n\n<h2>Helper function</h2>\n\n<p>If you have more images, and you want to ease the process of output them in templates you can create a custom function that wraps <code>get_template_directory_uri()</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>function theme_image( $image ) {\n return get_template_directory_uri() . '/site/images/' . $image;\n}\n</code></pre>\n\n<p>and then in templates do:</p>\n\n<pre><code><img src=\"<?php echo theme_image('footLogo.png') ?>\" \n style=\"padding: 0px!important; color:white\">\n</code></pre>\n\n<h2>WordPress 4.7+ and \"parent theme fallback\"</h2>\n\n<p>If you use WP 4.7+ code, you will have access to the new function <code>get_theme_file_uri()</code>.</p>\n\n<p>The benefit of this function over <code>get_template_directory_uri()</code> is that it automatically loads the file from child theme if available.</p>\n\n<p>So, for example, if you change the <code>theme_image()</code> function to:</p>\n\n<pre><code>function theme_image( $image ) {\n return get_theme_file_uri( '/site/images/' . $image );\n}\n</code></pre>\n\n<p>when you do <code>theme_image('footLogo.png')</code> the image <code>'footLogo.png'</code> will be loaded from child theme, if child theme is in use and the file is available there, otherwise will be loaded from parent theme.</p>\n\n<p>This new feature provides a \"parent theme fallback\" that pairs with the \"template parent theme fallback\" from parent to child themes that has been there since WP 3.0 through functions like <code>get_template_part()</code>.</p>\n"
},
{
"answer_id": 253011,
"author": "Savan Dholu",
"author_id": 108472,
"author_profile": "https://wordpress.stackexchange.com/users/108472",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot use PHP in the content editor, just write the full path to your image.</p>\n\n<pre><code><img src=\"/css/_include/img/slider-images/1.jpg\" alt=\"Image\" data-fullwidthcentering=\"on\">\n</code></pre>\n"
}
] |
2017/01/15
|
[
"https://wordpress.stackexchange.com/questions/252559",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110935/"
] |
I have image file stored inside theme directory called site.
Now in my home page using wordpress page editor I have put the following code but it didn't display image, seems location is wrong.
```
<img src="site/images/footLogo.png" style="padding: 0px!important; color:white">
```
let me know what issue?
|
You can define constant in theme function file as:
```
if( !defined(THEME_IMG_PATH)){
define( 'THEME_IMG_PATH', get_stylesheet_directory_uri() . '/site/images' );
}
```
and then you can use img tag as
```
<img src="<?php echo THEME_IMG_PATH; ?>/footLogo.png" style="padding: 0px!important; color:white">
```
|
252,595 |
<p>Here's the codes i used to display the posts of my custom post "episode"</p>
<pre><code><?php
if( is_home() ){
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array('post_type'=>array('episodes',),'paged'=>$paged ) ); } ?>
<?php if (have_posts()) : ?>
<?php post_movies_true(); ?>
<?php while (have_posts()) : the_post(); {?>
</code></pre>
<p>How can i add post_per_page there to limit the posts of my custom post?</p>
<p>PS: i dont really know how to code im just trying to do some custom modification with the theme i bought. I would really appreciate any help. Thanks.</p>
|
[
{
"answer_id": 252561,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": 1,
"selected": false,
"text": "<p>You'll have to copy the full path to the image like so:<br>\n<code>http://www.your-site-name.extension/wp-content/themes/site/images/footLogo.png</code> in your <code><img src=\"\"></code>.</p>\n\n<p>WordPress works with absolute urls.</p>\n"
},
{
"answer_id": 252563,
"author": "Muhammad Muazzam",
"author_id": 95126,
"author_profile": "https://wordpress.stackexchange.com/users/95126",
"pm_score": 2,
"selected": true,
"text": "<p>You can define constant in theme function file as:</p>\n\n<pre><code>if( !defined(THEME_IMG_PATH)){\n define( 'THEME_IMG_PATH', get_stylesheet_directory_uri() . '/site/images' );\n }\n</code></pre>\n\n<p>and then you can use img tag as</p>\n\n<pre><code> <img src=\"<?php echo THEME_IMG_PATH; ?>/footLogo.png\" style=\"padding: 0px!important; color:white\">\n</code></pre>\n"
},
{
"answer_id": 252572,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<h2>Absolute URLs</h2>\n\n<p>As other have said, you need to use the full URL for your image <code>src</code> attribute, or the browser will not be able to find it.</p>\n\n<p>WordPress provides the function <code>get_template_directory_uri()</code> that returns the full URL to your theme path.</p>\n\n<p>So, by doing:</p>\n\n<pre><code><?php\n$img_src = get_template_directory_uri() . '/site/images/footLogo.png';\n?>\n\n<img src=\"<?php echo $img_src ?>\" style=\"padding: 0px!important; color:white\">\n</code></pre>\n\n<p>your image will be shown, assuming the path is correct and the file is there.</p>\n\n<h2>Helper function</h2>\n\n<p>If you have more images, and you want to ease the process of output them in templates you can create a custom function that wraps <code>get_template_directory_uri()</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>function theme_image( $image ) {\n return get_template_directory_uri() . '/site/images/' . $image;\n}\n</code></pre>\n\n<p>and then in templates do:</p>\n\n<pre><code><img src=\"<?php echo theme_image('footLogo.png') ?>\" \n style=\"padding: 0px!important; color:white\">\n</code></pre>\n\n<h2>WordPress 4.7+ and \"parent theme fallback\"</h2>\n\n<p>If you use WP 4.7+ code, you will have access to the new function <code>get_theme_file_uri()</code>.</p>\n\n<p>The benefit of this function over <code>get_template_directory_uri()</code> is that it automatically loads the file from child theme if available.</p>\n\n<p>So, for example, if you change the <code>theme_image()</code> function to:</p>\n\n<pre><code>function theme_image( $image ) {\n return get_theme_file_uri( '/site/images/' . $image );\n}\n</code></pre>\n\n<p>when you do <code>theme_image('footLogo.png')</code> the image <code>'footLogo.png'</code> will be loaded from child theme, if child theme is in use and the file is available there, otherwise will be loaded from parent theme.</p>\n\n<p>This new feature provides a \"parent theme fallback\" that pairs with the \"template parent theme fallback\" from parent to child themes that has been there since WP 3.0 through functions like <code>get_template_part()</code>.</p>\n"
},
{
"answer_id": 253011,
"author": "Savan Dholu",
"author_id": 108472,
"author_profile": "https://wordpress.stackexchange.com/users/108472",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot use PHP in the content editor, just write the full path to your image.</p>\n\n<pre><code><img src=\"/css/_include/img/slider-images/1.jpg\" alt=\"Image\" data-fullwidthcentering=\"on\">\n</code></pre>\n"
}
] |
2017/01/15
|
[
"https://wordpress.stackexchange.com/questions/252595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110405/"
] |
Here's the codes i used to display the posts of my custom post "episode"
```
<?php
if( is_home() ){
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array('post_type'=>array('episodes',),'paged'=>$paged ) ); } ?>
<?php if (have_posts()) : ?>
<?php post_movies_true(); ?>
<?php while (have_posts()) : the_post(); {?>
```
How can i add post\_per\_page there to limit the posts of my custom post?
PS: i dont really know how to code im just trying to do some custom modification with the theme i bought. I would really appreciate any help. Thanks.
|
You can define constant in theme function file as:
```
if( !defined(THEME_IMG_PATH)){
define( 'THEME_IMG_PATH', get_stylesheet_directory_uri() . '/site/images' );
}
```
and then you can use img tag as
```
<img src="<?php echo THEME_IMG_PATH; ?>/footLogo.png" style="padding: 0px!important; color:white">
```
|
252,609 |
<p>i want show last 3 days posts Randomly.
how can i edit this code?</p>
<pre><code><?php
$randompost = array(
'numberposts' => 2,
'type' => 'news',
'orderby' => 'rand',
'year' => date( 'Y' ),
'week' => date( 'W' ),
);
$rand_posts = get_posts( $randompost );
foreach( $rand_posts as $post ) : ?>
<?php endforeach; ?>
</code></pre>
|
[
{
"answer_id": 252621,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the code below:</p>\n\n<pre><code>$today = getdate();\n$randompost = array(\n 'date_query' => array(\n array(\n 'before' => '3 days ago',\n 'after' => array(\n 'year' => $today['year'],\n 'month' => $today['mon'],\n 'day' => $today['mday'],\n ),\n ),\n ),\n 'numberposts' => 2,\n 'type' => 'news',\n 'orderby' => 'rand',\n );\n\n$rand_posts = get_posts( $randompost );\nif ( $rand_posts ) {\nforeach ( $rand_posts as $post ) : \n setup_postdata( $post );\n ?>\n <!-- Your Markup Here -->\n <?php\nendforeach; \nwp_reset_postdata();\n}\n?>\n</code></pre>\n\n<p>See more details <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 252671,
"author": "Jayesh",
"author_id": 98501,
"author_profile": "https://wordpress.stackexchange.com/users/98501",
"pm_score": 1,
"selected": true,
"text": "<p>You can use this code for show last 3 days post. Best of luck... </p>\n\n<pre><code>$args = array(\n 'post_status' => 'publish',\n 'type' => 'news',\n 'posts_per_page' => 2,\n 'order' => 'rand',\n 'date_query' => array(\n array(\n 'after' => '3 days ago'\n )\n )\n);\n</code></pre>\n"
}
] |
2017/01/15
|
[
"https://wordpress.stackexchange.com/questions/252609",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107899/"
] |
i want show last 3 days posts Randomly.
how can i edit this code?
```
<?php
$randompost = array(
'numberposts' => 2,
'type' => 'news',
'orderby' => 'rand',
'year' => date( 'Y' ),
'week' => date( 'W' ),
);
$rand_posts = get_posts( $randompost );
foreach( $rand_posts as $post ) : ?>
<?php endforeach; ?>
```
|
You can use this code for show last 3 days post. Best of luck...
```
$args = array(
'post_status' => 'publish',
'type' => 'news',
'posts_per_page' => 2,
'order' => 'rand',
'date_query' => array(
array(
'after' => '3 days ago'
)
)
);
```
|
252,620 |
<p>As in wordpress multi site, wordpress removed "Ping List Text Area" from Setting->Writing added Text Field in Network-Admin->All-Sites->Edit->Settings, I'm not able to understand that How we should add Ping List Url in text field.
Eg.:
http ://xyz [dot] com/rpc2 , http ://xyz1 [dot] com/rpc2
or
http ://xyz [dot] com/rpc2 http ://xyz1[dot]com/rpc2</p>
<p>Please explain that what we should use between two url, comma or space?</p>
|
[
{
"answer_id": 252621,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the code below:</p>\n\n<pre><code>$today = getdate();\n$randompost = array(\n 'date_query' => array(\n array(\n 'before' => '3 days ago',\n 'after' => array(\n 'year' => $today['year'],\n 'month' => $today['mon'],\n 'day' => $today['mday'],\n ),\n ),\n ),\n 'numberposts' => 2,\n 'type' => 'news',\n 'orderby' => 'rand',\n );\n\n$rand_posts = get_posts( $randompost );\nif ( $rand_posts ) {\nforeach ( $rand_posts as $post ) : \n setup_postdata( $post );\n ?>\n <!-- Your Markup Here -->\n <?php\nendforeach; \nwp_reset_postdata();\n}\n?>\n</code></pre>\n\n<p>See more details <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 252671,
"author": "Jayesh",
"author_id": 98501,
"author_profile": "https://wordpress.stackexchange.com/users/98501",
"pm_score": 1,
"selected": true,
"text": "<p>You can use this code for show last 3 days post. Best of luck... </p>\n\n<pre><code>$args = array(\n 'post_status' => 'publish',\n 'type' => 'news',\n 'posts_per_page' => 2,\n 'order' => 'rand',\n 'date_query' => array(\n array(\n 'after' => '3 days ago'\n )\n )\n);\n</code></pre>\n"
}
] |
2017/01/15
|
[
"https://wordpress.stackexchange.com/questions/252620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110962/"
] |
As in wordpress multi site, wordpress removed "Ping List Text Area" from Setting->Writing added Text Field in Network-Admin->All-Sites->Edit->Settings, I'm not able to understand that How we should add Ping List Url in text field.
Eg.:
http ://xyz [dot] com/rpc2 , http ://xyz1 [dot] com/rpc2
or
http ://xyz [dot] com/rpc2 http ://xyz1[dot]com/rpc2
Please explain that what we should use between two url, comma or space?
|
You can use this code for show last 3 days post. Best of luck...
```
$args = array(
'post_status' => 'publish',
'type' => 'news',
'posts_per_page' => 2,
'order' => 'rand',
'date_query' => array(
array(
'after' => '3 days ago'
)
)
);
```
|
252,622 |
<p>I'm using the plugin 'Ninja From' and I'm trying to stop it from loading a CSS file in the header.</p>
<p>The CSS file:</p>
<pre><code><link rel='stylesheet' id='nf-display-css' href='http://example.com/wp-content/plugins/ninja-forms/assets/css/display-structure.css?ver=4.7.1' type='text/css' media='all' />
</code></pre>
<p>My code:</p>
<pre><code>function remove_css_ninja_form(){
wp_dequeue_style('nf-display-css');
wp_deregister_style('nf-display-css');
}
add_action( 'wp_enqueue_scripts', 'remove_css_ninja_form', 99999 );
add_action( 'wp_print_styles', 'remove_css_ninja_form', 99999 );
add_action( 'wp_head', 'remove_css_ninja_form', 9999 );
</code></pre>
<p>It is not working.</p>
|
[
{
"answer_id": 252623,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": -1,
"selected": false,
"text": "<p>In WordPress priority <code>$arg</code>, <em>Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.</em></p>\n\n<p>So in your functions file, I'd suggest you use:</p>\n\n<pre><code>add_action( 'wp_head', 'remove_css_ninja_form', 0 );\n</code></pre>\n"
},
{
"answer_id": 252635,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>Extract the ninja form plugin's files to a folder, and use a text editor such as Notepad++ to search within the files of the plugin and find either one of these phrases: </p>\n\n<pre><code>`wp_enqueue_style` OR `css_ninja_form`\n</code></pre>\n\n<p>You will end up with at least 1 result, which will be similar to : </p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'css_ninja_form', xyz );\n</code></pre>\n\n<p>Which xyz is the priority the author of the plugin used to enqueue it. Now, you can directly remove the line from the result page (not recommended) or you can use the xyz priority to dequeue the script in your function.php.</p>\n"
},
{
"answer_id": 356200,
"author": "Milton Pena",
"author_id": 180933,
"author_profile": "https://wordpress.stackexchange.com/users/180933",
"pm_score": 0,
"selected": false,
"text": "<p>You need to dequeue the style in <code>nf_display_enqueue_scripts</code> like this :</p>\n\n<pre><code>add_action('nf_display_enqueue_scripts', function () {\n wp_dequeue_style('nf-font-awesome');\n wp_dequeue_style('nf-display');\n});\n</code></pre>\n"
}
] |
2017/01/15
|
[
"https://wordpress.stackexchange.com/questions/252622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110964/"
] |
I'm using the plugin 'Ninja From' and I'm trying to stop it from loading a CSS file in the header.
The CSS file:
```
<link rel='stylesheet' id='nf-display-css' href='http://example.com/wp-content/plugins/ninja-forms/assets/css/display-structure.css?ver=4.7.1' type='text/css' media='all' />
```
My code:
```
function remove_css_ninja_form(){
wp_dequeue_style('nf-display-css');
wp_deregister_style('nf-display-css');
}
add_action( 'wp_enqueue_scripts', 'remove_css_ninja_form', 99999 );
add_action( 'wp_print_styles', 'remove_css_ninja_form', 99999 );
add_action( 'wp_head', 'remove_css_ninja_form', 9999 );
```
It is not working.
|
Extract the ninja form plugin's files to a folder, and use a text editor such as Notepad++ to search within the files of the plugin and find either one of these phrases:
```
`wp_enqueue_style` OR `css_ninja_form`
```
You will end up with at least 1 result, which will be similar to :
```
add_action( 'wp_enqueue_scripts', 'css_ninja_form', xyz );
```
Which xyz is the priority the author of the plugin used to enqueue it. Now, you can directly remove the line from the result page (not recommended) or you can use the xyz priority to dequeue the script in your function.php.
|
252,640 |
<p>I have implemented AAPL on a new website which loads in Wordpress pages using AJAX.</p>
<p>Problem: For some unknown reason, css styles which are supposed to be loaded via enqueue are not being loaded.</p>
<p>If I click a page, some effects and transitions don't load - when checking the element, the css isn't visible. I then click "reload" which loads the page normally, and everything works perfectly.</p>
<p>Site: <a href="http://murrayfredericks.oleymedia.com/projects/" rel="nofollow noreferrer">http://murrayfredericks.oleymedia.com/projects/</a></p>
<p>Click "Greenlands" -> "Information" - you can see it loads the font in Times New Roman instead of the styles from bootstrap.css.
Reload the page and voila - problem resolved - bootstrap.css is loaded?</p>
<p>E.g.
When I click the "Information" page and view the source for the first column element:</p>
<pre><code><div class="wpb_column vc_column_container vc_col-sm-3 catlistli visible">
</code></pre>
<p>This is what I see:</p>
<p><a href="https://i.stack.imgur.com/uPWAI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uPWAI.png" alt="enter image description here"></a></p>
<p>Then, when I reload, I view the exact same element and this is what I see:</p>
<p><a href="https://i.stack.imgur.com/wzUYg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wzUYg.png" alt="enter image description here"></a></p>
<p>NOTE: See now that the js_composer.min.css is now being applied to the same element and is formatting it properly so that it looks how it should look.</p>
<p>It seems to never be the /child-theme/style.css that isn't applied - it's only ever js_composer.css or bootstrap.css</p>
|
[
{
"answer_id": 252623,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": -1,
"selected": false,
"text": "<p>In WordPress priority <code>$arg</code>, <em>Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.</em></p>\n\n<p>So in your functions file, I'd suggest you use:</p>\n\n<pre><code>add_action( 'wp_head', 'remove_css_ninja_form', 0 );\n</code></pre>\n"
},
{
"answer_id": 252635,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>Extract the ninja form plugin's files to a folder, and use a text editor such as Notepad++ to search within the files of the plugin and find either one of these phrases: </p>\n\n<pre><code>`wp_enqueue_style` OR `css_ninja_form`\n</code></pre>\n\n<p>You will end up with at least 1 result, which will be similar to : </p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'css_ninja_form', xyz );\n</code></pre>\n\n<p>Which xyz is the priority the author of the plugin used to enqueue it. Now, you can directly remove the line from the result page (not recommended) or you can use the xyz priority to dequeue the script in your function.php.</p>\n"
},
{
"answer_id": 356200,
"author": "Milton Pena",
"author_id": 180933,
"author_profile": "https://wordpress.stackexchange.com/users/180933",
"pm_score": 0,
"selected": false,
"text": "<p>You need to dequeue the style in <code>nf_display_enqueue_scripts</code> like this :</p>\n\n<pre><code>add_action('nf_display_enqueue_scripts', function () {\n wp_dequeue_style('nf-font-awesome');\n wp_dequeue_style('nf-display');\n});\n</code></pre>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10368/"
] |
I have implemented AAPL on a new website which loads in Wordpress pages using AJAX.
Problem: For some unknown reason, css styles which are supposed to be loaded via enqueue are not being loaded.
If I click a page, some effects and transitions don't load - when checking the element, the css isn't visible. I then click "reload" which loads the page normally, and everything works perfectly.
Site: <http://murrayfredericks.oleymedia.com/projects/>
Click "Greenlands" -> "Information" - you can see it loads the font in Times New Roman instead of the styles from bootstrap.css.
Reload the page and voila - problem resolved - bootstrap.css is loaded?
E.g.
When I click the "Information" page and view the source for the first column element:
```
<div class="wpb_column vc_column_container vc_col-sm-3 catlistli visible">
```
This is what I see:
[](https://i.stack.imgur.com/uPWAI.png)
Then, when I reload, I view the exact same element and this is what I see:
[](https://i.stack.imgur.com/wzUYg.png)
NOTE: See now that the js\_composer.min.css is now being applied to the same element and is formatting it properly so that it looks how it should look.
It seems to never be the /child-theme/style.css that isn't applied - it's only ever js\_composer.css or bootstrap.css
|
Extract the ninja form plugin's files to a folder, and use a text editor such as Notepad++ to search within the files of the plugin and find either one of these phrases:
```
`wp_enqueue_style` OR `css_ninja_form`
```
You will end up with at least 1 result, which will be similar to :
```
add_action( 'wp_enqueue_scripts', 'css_ninja_form', xyz );
```
Which xyz is the priority the author of the plugin used to enqueue it. Now, you can directly remove the line from the result page (not recommended) or you can use the xyz priority to dequeue the script in your function.php.
|
252,645 |
<p>I am new in wordpress, and I want to change a word in theme,for example in one of pages I have "view all" word, I want to change it to "see all"
How can i do this?</p>
|
[
{
"answer_id": 252646,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 3,
"selected": true,
"text": "<p>Some would say it is hard to answer based on the few information you provided.</p>\n\n<p>However, the answer may be general enough to cover many more problems similar to your case.</p>\n\n<p>First I would install this <a href=\"https://wordpress.org/plugins/show-current-template/\" rel=\"nofollow noreferrer\">plugin</a>.</p>\n\n<p>Check the screenshots section for more info:\n<a href=\"https://wordpress.org/plugins/show-current-template/screenshots/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/show-current-template/screenshots/</a></p>\n\n<p>It will provide you the list of files in use. This may be handy when you search where to edit your theme.</p>\n\n<p>Editing themes directly is not recommended, but if you don't care and just need to make it work than it is OK.</p>\n\n<p>Normally you would create the child theme, or work on your translation for the theme.</p>\n\n<p>You can use this kind of hooking to replace some string with another string for the whole theme if you add this to the <code>functions.php</code> file</p>\n\n<pre><code>function _20170116_replace_text ( $text ) {\n // possible add the condition when ...\n if ($text == 'View All'){$text = 'See All';}\n return $text;\n\n}\nadd_filter( 'gettext', '_20170116_replace_text' );\n</code></pre>\n\n<p>Check this and let me know if this works. With the <code>show-current-template</code> you can thinker the condition when to replace this text. </p>\n\n<p>The condition you need to add to <code>20170116_replace_text</code> may look like this:</p>\n\n<pre><code>if (in_array( $GLOBALS['pagenow'], array( 'your-page.php' ) )) {\n}\n</code></pre>\n"
},
{
"answer_id": 252668,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>If your theme is using something like <code><?php _e( 'View All' ); ?></code> to render the texts, then it is probably using a language file that contains every string on the template. </p>\n\n<ol>\n<li>Download <a href=\"https://poedit.net/\" rel=\"nofollow noreferrer\">this</a> application. It can be used to translate the wordpress language files.</li>\n<li>Verify that there is a folder named <code>langauge</code> in your theme's folder. Browse inside the folder, and you will find some files in <code>.po</code> and <code>.mo</code> extension. </li>\n<li>Use Poedit to translate the proper file based on your need. It will be <code>en_US.po</code> in case you are using english as your main language.</li>\n<li>If the file <code>en_US.po</code> didn't exist, then you can advance with other solutions.</li>\n</ol>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252645",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110983/"
] |
I am new in wordpress, and I want to change a word in theme,for example in one of pages I have "view all" word, I want to change it to "see all"
How can i do this?
|
Some would say it is hard to answer based on the few information you provided.
However, the answer may be general enough to cover many more problems similar to your case.
First I would install this [plugin](https://wordpress.org/plugins/show-current-template/).
Check the screenshots section for more info:
<https://wordpress.org/plugins/show-current-template/screenshots/>
It will provide you the list of files in use. This may be handy when you search where to edit your theme.
Editing themes directly is not recommended, but if you don't care and just need to make it work than it is OK.
Normally you would create the child theme, or work on your translation for the theme.
You can use this kind of hooking to replace some string with another string for the whole theme if you add this to the `functions.php` file
```
function _20170116_replace_text ( $text ) {
// possible add the condition when ...
if ($text == 'View All'){$text = 'See All';}
return $text;
}
add_filter( 'gettext', '_20170116_replace_text' );
```
Check this and let me know if this works. With the `show-current-template` you can thinker the condition when to replace this text.
The condition you need to add to `20170116_replace_text` may look like this:
```
if (in_array( $GLOBALS['pagenow'], array( 'your-page.php' ) )) {
}
```
|
252,658 |
<p>Need to switch theme when accessed from sub domain. There is nothing installed in the sub domain. I have setup a subdomain as a CNAME pointing to the original domain. Then, detect whether or not the visitor is on the subdomain by looking at $_SERVER[‘SERVER_NAME’]. Went through various sources and have found out this code but could not make this working.</p>
<p>Note: I am a newbie</p>
<pre><code>// regular site url
$my_url = 'http://example.com';
// subdomain you want a different theme on
$my_sub_url = 'http://sub.example.com';
// subdomain prefix, used to test whether primary or subdomain
$my_prefix = 'sub.';
// folder name of theme to use instead on subdomain
$my_theme_name = 'my_mobile_theme';
add_filter( 'template' , 'my_change_theme' );
add_filter( 'option_template' , 'my_change_theme' );
add_filter( 'option_stylesheet' , 'my_change_theme' );
// these 2 actions rewrite all urls in the body
// from main to sub domain
add_action( 'wp_head' , 'my_buffer_start' );
add_action( 'wp_footer' , 'my_buffer_end' );
// TRUE, if this is the subdomain, false otherwise
public function my_is_subdomain() {
global $my_prefix;
if( strpos( $_SERVER['SERVER_NAME'], $my_prefix ) !== FALSE ) {
return TRUE;
}
return FALSE;
}
// if this is the subdomain, return new theme
// otherwise, return original theme
public function my_change_theme( $theme ) {
global $my_theme_name;
if( my_is_subdomain() ) {
return $my_theme_name;
}
return $theme;
}
public function my_buffer_start() {
ob_start('my_buffer_cb');
}
public function my_buffer_end() {
ob_end_flush();
}
// replace primary url with subdomain url in body
// so that all links keep user on the subdomain
public function my_buffer_cb( $buffer ) {
global $my__url, $my_sub_url;
if( ! my_is_subdomain() ) {
return $buffer;
}
// replace main domain with sub domain
$buffer = str_replace( $my_url, $my_sub_url, $buffer);
// !!! NOTE - you may not want to replace EVERY instance
// for example, you may want to keep social media urls
// intact, or rel="canonical", or links specifically
// designed to switch between the primary and subdomain
return $buffer;
}
</code></pre>
|
[
{
"answer_id": 252665,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress supports only one theme on site. Actions like shown will cause a adverse effects.\nInstead, you should use WordPress Multisite, which allows to use different themes on subdomains. This is the way recommended by the WordPress team.</p>\n\n<p>There is solution for WooCommerce on WordPress Multisite: <a href=\"https://woomultistore.com\" rel=\"nofollow noreferrer\">WooCommerce Multistore plugin:</a> It is quite expensive ($200), but struggling with unsupported features in WordPress can cost much more.</p>\n"
},
{
"answer_id": 370620,
"author": "ThomasV",
"author_id": 151036,
"author_profile": "https://wordpress.stackexchange.com/users/151036",
"pm_score": 0,
"selected": false,
"text": "<p>I would not recommend The Woocommerce Multistore plugin as described in KAGG Design's answer.</p>\n<p>It's overall very slow, which is very bad for the stock synchronization.\nIt also supports WPML which is one of the worst plugins, that overloading your database and will kill your store overtime.</p>\n<p>For this reason I went with Woocommerce Multistore by Mrinvent.\nIt's a platform that manages realtime stock synchronization, PIM management, order management and Multilingual.</p>\n<p>You can pay per month, which makes it cheaper and easier to try.</p>\n<p><a href=\"https://mrinvent.online\" rel=\"nofollow noreferrer\">https://mrinvent.online</a></p>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252658",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111003/"
] |
Need to switch theme when accessed from sub domain. There is nothing installed in the sub domain. I have setup a subdomain as a CNAME pointing to the original domain. Then, detect whether or not the visitor is on the subdomain by looking at $\_SERVER[‘SERVER\_NAME’]. Went through various sources and have found out this code but could not make this working.
Note: I am a newbie
```
// regular site url
$my_url = 'http://example.com';
// subdomain you want a different theme on
$my_sub_url = 'http://sub.example.com';
// subdomain prefix, used to test whether primary or subdomain
$my_prefix = 'sub.';
// folder name of theme to use instead on subdomain
$my_theme_name = 'my_mobile_theme';
add_filter( 'template' , 'my_change_theme' );
add_filter( 'option_template' , 'my_change_theme' );
add_filter( 'option_stylesheet' , 'my_change_theme' );
// these 2 actions rewrite all urls in the body
// from main to sub domain
add_action( 'wp_head' , 'my_buffer_start' );
add_action( 'wp_footer' , 'my_buffer_end' );
// TRUE, if this is the subdomain, false otherwise
public function my_is_subdomain() {
global $my_prefix;
if( strpos( $_SERVER['SERVER_NAME'], $my_prefix ) !== FALSE ) {
return TRUE;
}
return FALSE;
}
// if this is the subdomain, return new theme
// otherwise, return original theme
public function my_change_theme( $theme ) {
global $my_theme_name;
if( my_is_subdomain() ) {
return $my_theme_name;
}
return $theme;
}
public function my_buffer_start() {
ob_start('my_buffer_cb');
}
public function my_buffer_end() {
ob_end_flush();
}
// replace primary url with subdomain url in body
// so that all links keep user on the subdomain
public function my_buffer_cb( $buffer ) {
global $my__url, $my_sub_url;
if( ! my_is_subdomain() ) {
return $buffer;
}
// replace main domain with sub domain
$buffer = str_replace( $my_url, $my_sub_url, $buffer);
// !!! NOTE - you may not want to replace EVERY instance
// for example, you may want to keep social media urls
// intact, or rel="canonical", or links specifically
// designed to switch between the primary and subdomain
return $buffer;
}
```
|
WordPress supports only one theme on site. Actions like shown will cause a adverse effects.
Instead, you should use WordPress Multisite, which allows to use different themes on subdomains. This is the way recommended by the WordPress team.
There is solution for WooCommerce on WordPress Multisite: [WooCommerce Multistore plugin:](https://woomultistore.com) It is quite expensive ($200), but struggling with unsupported features in WordPress can cost much more.
|
252,680 |
<p><strong>TL;DR</strong> - Why is my user account not logged in during an AJAX request which is made inside wp-admin?</p>
<hr>
<p>I have the following setup:</p>
<pre><code><?php
add_action('wp_ajax_foobar_action', 'foobar_action');
add_action('wp_ajax_nopriv_foobar_action', 'foobar_action');
function foobar_action() {
check_ajax_referrer();
wp_send_json((object) ['msg' => 'hello world']);
}
add_action('admin_print_scripts', function () {
printf('<script type="text/javascript">window.custom_nonce = "%s";</script>', wp_create_nonce());
});
</code></pre>
<p>And in JS:</p>
<pre><code>var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce
}).then(function (res) {
msg = res.json().msg;
});
</code></pre>
<p>This is all run in wp-admin. The issue is that the wp-admin page/JS script itself is loaded as a logged in user, but the AJAX request that ends up into admin-ajax.php is done as a logged out guest user. This leads to the issue of wp-admin using <code>nopriv</code> and <code>check_ajax_referrer</code> failing 100% of the time.</p>
<p>Why does wp-admin make AJAX requests as a guest instead of the logged in user?</p>
<p>Currently, the AJAX endpoint returns <code>403</code> status with <code>-1</code> content, as it should in case there is a nonce mismatch. If I comment out the <code>check_ajax_referrer()</code> call then the AJAX request runs through successfully. After some furious <code>console.log</code>ging I've determined that the nonce values match in the JS fetch call and the AJAX endpoint that receives it (which means the nonce is properly transferred, but a wrong guest nonce is generated during the AJAX endpoint execution.</p>
<p>If I remove the <code>wp_ajax_nopriv_foobar_action</code> then WordPress doesn't find the auth-enabled AJAX action because there seemingly is no logged in user available (results in status <code>200</code> and body <code>0</code>).</p>
<p>Steps I've attempted to fix the issue:</p>
<ul>
<li>Logged out and in again, cleared caches/cookies, used incognito windows,</li>
<li>Restarted PHP-FPM, Nginx, object cache backends, MariaDB,</li>
<li>Disabled all plugins that are not required for operation,</li>
<li>Moved the AJAX hooking code around in my plugin code, all the way to the plugin root file (e.g. <code>myplugin/myplugin.php</code>),</li>
<li>Used GET instead of POST.</li>
</ul>
|
[
{
"answer_id": 252683,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>I think problem could be due to the consequence: </p>\n\n<p>in HTML source, firstly, this should be outputed: <code>.......... window.custom_nonce = \"%s\" ...</code> and then should be called <code>fetch</code> function. In <code>foobar_action()</code>, add this line: <code>var_dump(is_user_logged_in());</code> and see, maybe it detects login (if so, then reason is in nonce. Otherwise, problem is in <code>login</code>)</p>\n\n<p>p.s. Have you tried changing POST to GET method?</p>\n"
},
{
"answer_id": 252687,
"author": "ojrask",
"author_id": 34299,
"author_profile": "https://wordpress.stackexchange.com/users/34299",
"pm_score": 3,
"selected": false,
"text": "<p>After some fiddling and sparring with @t-todua I found the issue:</p>\n\n<p>With the Fetch API <code>fetch</code> call you must manually set to send cookies with a request. After setting the <code>credentials</code> option properly the cookies were sent and the AJAX endpoint recognized the current user. So the JS becomes:</p>\n\n<pre><code>var msg = '';\n\n// I'm using the whatwg-fetch polyfill and a polyfill for Promises.\nfetch(ajaxurl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'\n },\n body: 'action=foobar_action&_wpnonce=' + window.custom_nonce,\n credentials: 'same-origin'\n}).then(function (res) {\n msg = res.json().msg;\n});\n</code></pre>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252680",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34299/"
] |
**TL;DR** - Why is my user account not logged in during an AJAX request which is made inside wp-admin?
---
I have the following setup:
```
<?php
add_action('wp_ajax_foobar_action', 'foobar_action');
add_action('wp_ajax_nopriv_foobar_action', 'foobar_action');
function foobar_action() {
check_ajax_referrer();
wp_send_json((object) ['msg' => 'hello world']);
}
add_action('admin_print_scripts', function () {
printf('<script type="text/javascript">window.custom_nonce = "%s";</script>', wp_create_nonce());
});
```
And in JS:
```
var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce
}).then(function (res) {
msg = res.json().msg;
});
```
This is all run in wp-admin. The issue is that the wp-admin page/JS script itself is loaded as a logged in user, but the AJAX request that ends up into admin-ajax.php is done as a logged out guest user. This leads to the issue of wp-admin using `nopriv` and `check_ajax_referrer` failing 100% of the time.
Why does wp-admin make AJAX requests as a guest instead of the logged in user?
Currently, the AJAX endpoint returns `403` status with `-1` content, as it should in case there is a nonce mismatch. If I comment out the `check_ajax_referrer()` call then the AJAX request runs through successfully. After some furious `console.log`ging I've determined that the nonce values match in the JS fetch call and the AJAX endpoint that receives it (which means the nonce is properly transferred, but a wrong guest nonce is generated during the AJAX endpoint execution.
If I remove the `wp_ajax_nopriv_foobar_action` then WordPress doesn't find the auth-enabled AJAX action because there seemingly is no logged in user available (results in status `200` and body `0`).
Steps I've attempted to fix the issue:
* Logged out and in again, cleared caches/cookies, used incognito windows,
* Restarted PHP-FPM, Nginx, object cache backends, MariaDB,
* Disabled all plugins that are not required for operation,
* Moved the AJAX hooking code around in my plugin code, all the way to the plugin root file (e.g. `myplugin/myplugin.php`),
* Used GET instead of POST.
|
After some fiddling and sparring with @t-todua I found the issue:
With the Fetch API `fetch` call you must manually set to send cookies with a request. After setting the `credentials` option properly the cookies were sent and the AJAX endpoint recognized the current user. So the JS becomes:
```
var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce,
credentials: 'same-origin'
}).then(function (res) {
msg = res.json().msg;
});
```
|
252,689 |
<p>I have written following js code</p>
<pre><code>jQuery(".selectbox").change(function(){
var id = this.id;
var key_id=id;
var selectname='';
jQuery.post(
// see tip #1 for how we declare global javascript variables
MyAjax.ajaxurl,
{
// here we declare the parameters to send along with the request
// this means the following action hooks will be fired:
// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
action : 'get-mata-value',
// other parameters can be added along with "action"
prev_metakey : jQuery(this).val(),
metakey: key_id
},
function( result ) {
if(result['success'] != false)
{
jQuery.each(result,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
}
);
</code></pre>
<p>});</p>
<p>and function is:</p>
<pre><code>wp_localize_script( 'script', 'MyAjax',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
)
);
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/vehicle_parts.js', array ( 'jquery' ), 1.1, true);
add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$prev_value=$_POST["prev_metakey"];
$result=array();
$result=$wpdb->get_col("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = '$key'");
return($result);
}
</code></pre>
<p>when I change select box the function is not being called.</p>
|
[
{
"answer_id": 252683,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>I think problem could be due to the consequence: </p>\n\n<p>in HTML source, firstly, this should be outputed: <code>.......... window.custom_nonce = \"%s\" ...</code> and then should be called <code>fetch</code> function. In <code>foobar_action()</code>, add this line: <code>var_dump(is_user_logged_in());</code> and see, maybe it detects login (if so, then reason is in nonce. Otherwise, problem is in <code>login</code>)</p>\n\n<p>p.s. Have you tried changing POST to GET method?</p>\n"
},
{
"answer_id": 252687,
"author": "ojrask",
"author_id": 34299,
"author_profile": "https://wordpress.stackexchange.com/users/34299",
"pm_score": 3,
"selected": false,
"text": "<p>After some fiddling and sparring with @t-todua I found the issue:</p>\n\n<p>With the Fetch API <code>fetch</code> call you must manually set to send cookies with a request. After setting the <code>credentials</code> option properly the cookies were sent and the AJAX endpoint recognized the current user. So the JS becomes:</p>\n\n<pre><code>var msg = '';\n\n// I'm using the whatwg-fetch polyfill and a polyfill for Promises.\nfetch(ajaxurl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'\n },\n body: 'action=foobar_action&_wpnonce=' + window.custom_nonce,\n credentials: 'same-origin'\n}).then(function (res) {\n msg = res.json().msg;\n});\n</code></pre>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252689",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95126/"
] |
I have written following js code
```
jQuery(".selectbox").change(function(){
var id = this.id;
var key_id=id;
var selectname='';
jQuery.post(
// see tip #1 for how we declare global javascript variables
MyAjax.ajaxurl,
{
// here we declare the parameters to send along with the request
// this means the following action hooks will be fired:
// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
action : 'get-mata-value',
// other parameters can be added along with "action"
prev_metakey : jQuery(this).val(),
metakey: key_id
},
function( result ) {
if(result['success'] != false)
{
jQuery.each(result,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
}
);
```
});
and function is:
```
wp_localize_script( 'script', 'MyAjax',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
)
);
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/vehicle_parts.js', array ( 'jquery' ), 1.1, true);
add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$prev_value=$_POST["prev_metakey"];
$result=array();
$result=$wpdb->get_col("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = '$key'");
return($result);
}
```
when I change select box the function is not being called.
|
After some fiddling and sparring with @t-todua I found the issue:
With the Fetch API `fetch` call you must manually set to send cookies with a request. After setting the `credentials` option properly the cookies were sent and the AJAX endpoint recognized the current user. So the JS becomes:
```
var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce,
credentials: 'same-origin'
}).then(function (res) {
msg = res.json().msg;
});
```
|
252,700 |
<p>Sorry if it's a duplicate question,
I just want to change a little the WordPress core function <code>get_header()</code> with new function <code>new_get_header()</code>.</p>
<pre><code>function new_get_header() {
// new header fragments;
}
</code></pre>
<p><strong>Is this possible?</strong></p>
<pre><code>add_filter( 'get_header', 'new_get_header' );
</code></pre>
<p><strong>Or should I use:</strong></p>
<pre><code>add_action( 'init', 'new_get_header' );
</code></pre>
<p>And call it as a function instead of original.</p>
<pre><code>new_get_header();
// Content
// Footer
</code></pre>
|
[
{
"answer_id": 252683,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>I think problem could be due to the consequence: </p>\n\n<p>in HTML source, firstly, this should be outputed: <code>.......... window.custom_nonce = \"%s\" ...</code> and then should be called <code>fetch</code> function. In <code>foobar_action()</code>, add this line: <code>var_dump(is_user_logged_in());</code> and see, maybe it detects login (if so, then reason is in nonce. Otherwise, problem is in <code>login</code>)</p>\n\n<p>p.s. Have you tried changing POST to GET method?</p>\n"
},
{
"answer_id": 252687,
"author": "ojrask",
"author_id": 34299,
"author_profile": "https://wordpress.stackexchange.com/users/34299",
"pm_score": 3,
"selected": false,
"text": "<p>After some fiddling and sparring with @t-todua I found the issue:</p>\n\n<p>With the Fetch API <code>fetch</code> call you must manually set to send cookies with a request. After setting the <code>credentials</code> option properly the cookies were sent and the AJAX endpoint recognized the current user. So the JS becomes:</p>\n\n<pre><code>var msg = '';\n\n// I'm using the whatwg-fetch polyfill and a polyfill for Promises.\nfetch(ajaxurl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'\n },\n body: 'action=foobar_action&_wpnonce=' + window.custom_nonce,\n credentials: 'same-origin'\n}).then(function (res) {\n msg = res.json().msg;\n});\n</code></pre>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252700",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101492/"
] |
Sorry if it's a duplicate question,
I just want to change a little the WordPress core function `get_header()` with new function `new_get_header()`.
```
function new_get_header() {
// new header fragments;
}
```
**Is this possible?**
```
add_filter( 'get_header', 'new_get_header' );
```
**Or should I use:**
```
add_action( 'init', 'new_get_header' );
```
And call it as a function instead of original.
```
new_get_header();
// Content
// Footer
```
|
After some fiddling and sparring with @t-todua I found the issue:
With the Fetch API `fetch` call you must manually set to send cookies with a request. After setting the `credentials` option properly the cookies were sent and the AJAX endpoint recognized the current user. So the JS becomes:
```
var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce,
credentials: 'same-origin'
}).then(function (res) {
msg = res.json().msg;
});
```
|
252,709 |
<p>I am trying to figure out if it is possible to add elements to the widgetpage in WordPress' dashboard without editing the widgets.php core file. Is there a WordPress function or something else (maybe even a jQuery solution) that will get this done? </p>
<p>If I google this the only results are about widget area's but I just need to add an image (like really an img element, not a widget) to the widget page.</p>
<p>Is there anyone that knows if this is possible and give me some hint/help.</p>
|
[
{
"answer_id": 252721,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 0,
"selected": false,
"text": "<p>There is few <code>action</code> hooks in <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-admin/widgets.php\" rel=\"nofollow noreferrer\"><code>wp-admin/widgets.php</code></a> you need to check.\nAnd if you want to add a image in <strong>Widgets</strong> page i would recommend to use <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-admin/widgets.php#L379\" rel=\"nofollow noreferrer\"><code>widgets_admin_page</code></a> action hook. This hook fires right after Widgets page title and alert messages are print.</p>\n\n<pre><code>add_action( \"widgets_admin_page\", \"add_image_after_widget_page_title\" );\nfunction add_image_after_widget_page_title() {\n echo '<img src=\"path to your image\" alt=\"\">';\n}\n</code></pre>\n"
},
{
"answer_id": 252744,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>You can use @kudratullah's suggestion to hook into the widgets page. The downside is that this allows insertion of a piece of html only in one specific place. If that location is ok, use that solution.</p>\n\n<p>Otherwise, there are two other possibilities.</p>\n\n<p>The first is to use jquery. Examine the source to identify the html element where you want to add your image (let's say #wrap). Then <a href=\"http://api.jquery.com/append/\" rel=\"nofollow noreferrer\">append</a> the node like this:</p>\n\n<pre><code>$( \"#wrap\" ).append( \"<img src='....' />\" );\n</code></pre>\n\n<p>The second is to use the css after pseudoclass like this:</p>\n\n<pre><code>#wrap:after {content:url('/path/to/mypic.jpg');}\n</code></pre>\n\n<p>Both style and script files need to be <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow noreferrer\">enqueued to the admin</a>.</p>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111030/"
] |
I am trying to figure out if it is possible to add elements to the widgetpage in WordPress' dashboard without editing the widgets.php core file. Is there a WordPress function or something else (maybe even a jQuery solution) that will get this done?
If I google this the only results are about widget area's but I just need to add an image (like really an img element, not a widget) to the widget page.
Is there anyone that knows if this is possible and give me some hint/help.
|
You can use @kudratullah's suggestion to hook into the widgets page. The downside is that this allows insertion of a piece of html only in one specific place. If that location is ok, use that solution.
Otherwise, there are two other possibilities.
The first is to use jquery. Examine the source to identify the html element where you want to add your image (let's say #wrap). Then [append](http://api.jquery.com/append/) the node like this:
```
$( "#wrap" ).append( "<img src='....' />" );
```
The second is to use the css after pseudoclass like this:
```
#wrap:after {content:url('/path/to/mypic.jpg');}
```
Both style and script files need to be [enqueued to the admin](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts).
|
252,715 |
<p>I have created the following "plugin" following the codex but it doesn't seem to work. It is supposed to add 100 points to user meta everytime he/she posts a new blog post.</p>
<p>Could you please let me know what is wrong with it...</p>
<pre><code>function post_published_add_points( $ID, $post ) {
$author = $post->post_author; /* Post author ID. */
add_user_meta( $author, 'Points', '100');
}
add_action( 'publish_post', 'post_published_add_points', 10, 2 );
</code></pre>
<p>Thanks!
Dragos</p>
|
[
{
"answer_id": 252721,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 0,
"selected": false,
"text": "<p>There is few <code>action</code> hooks in <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-admin/widgets.php\" rel=\"nofollow noreferrer\"><code>wp-admin/widgets.php</code></a> you need to check.\nAnd if you want to add a image in <strong>Widgets</strong> page i would recommend to use <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-admin/widgets.php#L379\" rel=\"nofollow noreferrer\"><code>widgets_admin_page</code></a> action hook. This hook fires right after Widgets page title and alert messages are print.</p>\n\n<pre><code>add_action( \"widgets_admin_page\", \"add_image_after_widget_page_title\" );\nfunction add_image_after_widget_page_title() {\n echo '<img src=\"path to your image\" alt=\"\">';\n}\n</code></pre>\n"
},
{
"answer_id": 252744,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>You can use @kudratullah's suggestion to hook into the widgets page. The downside is that this allows insertion of a piece of html only in one specific place. If that location is ok, use that solution.</p>\n\n<p>Otherwise, there are two other possibilities.</p>\n\n<p>The first is to use jquery. Examine the source to identify the html element where you want to add your image (let's say #wrap). Then <a href=\"http://api.jquery.com/append/\" rel=\"nofollow noreferrer\">append</a> the node like this:</p>\n\n<pre><code>$( \"#wrap\" ).append( \"<img src='....' />\" );\n</code></pre>\n\n<p>The second is to use the css after pseudoclass like this:</p>\n\n<pre><code>#wrap:after {content:url('/path/to/mypic.jpg');}\n</code></pre>\n\n<p>Both style and script files need to be <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow noreferrer\">enqueued to the admin</a>.</p>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252715",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110131/"
] |
I have created the following "plugin" following the codex but it doesn't seem to work. It is supposed to add 100 points to user meta everytime he/she posts a new blog post.
Could you please let me know what is wrong with it...
```
function post_published_add_points( $ID, $post ) {
$author = $post->post_author; /* Post author ID. */
add_user_meta( $author, 'Points', '100');
}
add_action( 'publish_post', 'post_published_add_points', 10, 2 );
```
Thanks!
Dragos
|
You can use @kudratullah's suggestion to hook into the widgets page. The downside is that this allows insertion of a piece of html only in one specific place. If that location is ok, use that solution.
Otherwise, there are two other possibilities.
The first is to use jquery. Examine the source to identify the html element where you want to add your image (let's say #wrap). Then [append](http://api.jquery.com/append/) the node like this:
```
$( "#wrap" ).append( "<img src='....' />" );
```
The second is to use the css after pseudoclass like this:
```
#wrap:after {content:url('/path/to/mypic.jpg');}
```
Both style and script files need to be [enqueued to the admin](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts).
|
252,730 |
<p>I need to set 1 cookie, saving a data sent from a form.</p>
<p>I see that I have to hook my setcookie() to the 'init'. That's OK.</p>
<pre><code>add_action( 'init', 'cookie_function');
</code></pre>
<p>My 'cookie_function' will have $cookieName, $cookieValue, $time, COOKIEPATH, COOKIEDOMAIN.</p>
<p>If I need something like setcookie('test', $_POST['test']), what do I call:</p>
<pre><code>cookie_function() //and where do I pass parameters?
</code></pre>
<p>or</p>
<pre><code>setcookie() //and this function will be related to my cookie_function()?
</code></pre>
|
[
{
"answer_id": 252734,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>You use setcookie() like any other function, with parameters as described in the Codex. </p>\n\n<p>How you would use it in a form would usually depend on how and when the $_COOKIE variable needs to be made accessible. </p>\n\n<p>One common method, if you want a change in the DOM both to register immediately and to persist, is to use a Javascript/jQuery function whose effect is duplicated in the PHP functions that will draw upon $_COOKIE variables. The cookie will also typically be set or updated in the same script, commonly with the aid of jquery-cookie or js-cookie.</p>\n"
},
{
"answer_id": 252735,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>A cookie is name and value pair simplified. \nUse cookies to store data on the client side. </p>\n\n<p>In PHP you would define cookie like this:</p>\n\n<pre><code>setcookie( name, value, expire, path, domain, secure, httponly);\n</code></pre>\n\n<p>Cookies can be stolen via JavaScript but they may not be. It depends. </p>\n\n<p>The httponly flag, if set to true, means cookies cannot be altered via JavaScript.</p>\n\n<p>The secure flag purpose is to prevent clear text cookies over HTTP. By setting the secure flag, the browser will prevent the transmission of a cookie over an unencrypted channel.</p>\n\n<p>The other parameters like domain and path are constraints, that precisely set where cookie should work.</p>\n\n<p>For instance setting cookie domain to <code>www.example.com</code> will mean only the exact domain <code>www.example.com</code> will be matched, while <code>.example.com</code> will also match any subdomain (<code>forum.example.com</code>, <code>blog.example.com</code>).</p>\n\n<p>The path argument default value of <code>/</code> means every request will get the cookie, while <code>/forum/</code> limits the cookie to just <code>/forum</code> path.</p>\n\n<p>The expire flag is usually set to some period like 1 or 2 weeks meaning that the cookie will last for 1 or 2 weeks.</p>\n\n<blockquote>\n <p>I see that I have to hook my setcookie() to the 'init'. That's OK.</p>\n \n <p>$_POST['test']</p>\n</blockquote>\n\n<p>You don't need to use 'init' hook to set the cookie. This is not a must. Wherever you work with your form data in your code you simply use either <code>$_POST['test']</code> or <code>$_GET['test']</code> based on the form type. Also, no need to mention you need to check these variables first.</p>\n\n<p>Later you use something like this to check if the cookie is present.</p>\n\n<pre><code>if ( isset( $_COOKIE['name'] ) ) ...\n</code></pre>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252730",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111037/"
] |
I need to set 1 cookie, saving a data sent from a form.
I see that I have to hook my setcookie() to the 'init'. That's OK.
```
add_action( 'init', 'cookie_function');
```
My 'cookie\_function' will have $cookieName, $cookieValue, $time, COOKIEPATH, COOKIEDOMAIN.
If I need something like setcookie('test', $\_POST['test']), what do I call:
```
cookie_function() //and where do I pass parameters?
```
or
```
setcookie() //and this function will be related to my cookie_function()?
```
|
You use setcookie() like any other function, with parameters as described in the Codex.
How you would use it in a form would usually depend on how and when the $\_COOKIE variable needs to be made accessible.
One common method, if you want a change in the DOM both to register immediately and to persist, is to use a Javascript/jQuery function whose effect is duplicated in the PHP functions that will draw upon $\_COOKIE variables. The cookie will also typically be set or updated in the same script, commonly with the aid of jquery-cookie or js-cookie.
|
252,740 |
<p>I'm building currently a website on WordPress. The site has a custom post type. I have a customized search form, which selects entries from custom post type. Entries are being selected and sorted as they are supposed to, however on my search result page (job-search.php) I need a pagination, and it's not working, although same codes works fine on other pages. I see page number changing in browser's search bar, but I always see entries from first page.</p>
<p>Code for search form and query for custom post type with specified selections and filtering (inside job-search.php):</p>
<pre><code><?php
/*
* Template Name:job-search
*/
get_header();?>
<div>
<form method="get" action="<?php echo site_url('/'); ?>/job-search" >
<input type="search" name="job-name" placeholder="Job..." />
<input type="search" name="town-name" placeholder="Town..." />
<select type="search" name="date">
<option value="DESC">Datum absteigend</option>
<option value="ASC">Datum aufsteigend</option>
</select>
<div>
<input type="checkbox" name="cat[]" value="IT, Telekommunikation" />IT, Telekommunikation
<input type="checkbox" name="cat[]" value="Ingenieur, Technik" />Ingenieur, Technik
<input type="checkbox" name="cat[]" value="Handwerk, Gewerbe" />Handwerk, Gewerbe
</div>
<input type="submit" value="Search">
</form>
</div>
<?php
$jobName = $_GET['job-name'];
$jobTown = $_GET['town-name'];
$jobDate = $_GET['date'];
if($_GET['cat'] && !empty($_GET['cat'])){
$jobCat = $_GET['cat'];
}
else{
$jobCat = array('Vertrieb, Verkauf', 'IT, Telekommunikation', 'Ingenieur, Technik', 'Personalwesen', 'Bildung, Soziales', 'Einkauf, Logistik', 'Handwerk, Gewerbe', 'Führungskräfte', 'Marketing, PR', 'Medizin, Pflege', 'Finanzen, Steuern, Recht', 'Kaufmännische Berufe', 'Luft- und Raumfahrt, Reise', 'Ausbildung', '');
}
?>
<h1 style="font-size:1.5em; font-weight:bold; border-bottom:2px solid green; color:green; margin-bottom:20px;">wp_query_search results</h1>
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$q1 = array(
'post_type' => 'jobs',
's' => $jobName,
'posts_per_page' => 10,
'paged' => $paged,
'meta_key' => 'date',
'orderby' => 'meta_value',
'order' => $jobDate,
'meta_query' => array (
'relation' => 'AND',
array(
'key' => 'town',
'value' => $jobTown,
'compare' => 'LIKE'
),
array(
'relation' => 'OR',
array(
'key' => 'cat_1',
'value' => $jobCat
),
array(
'key' => 'cat_2',
'value' => $jobCat
)
)
)
);
$query = new WP_Query($q1);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post();?>
<h2 style="color:brown; font-weight:bold; border-bottom:1px dotted brown;"><?php the_field('title'); ?></h2>
<h3><?php the_field('town'); ?></h3>
<h4><?php the_field('cat_1'); ?> | <?php the_field('cat_2'); ?></h4>
<h5><?php the_field('date'); ?></h5>
<?php endwhile;
if (function_exists(search_pagination)) {
search_pagination($query->max_num_pages,"",$paged);
}
endif; wp_reset_query(); ?>
</div>
<?php get_footer(); ?>
</code></pre>
<p>Code for Pagination (inside functions.php):</p>
<pre><code>function search_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
$paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
//global $wp_query;
//$numpages = $wp_query->max_num_pages;
$numpages = $query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('&laquo;'),
'next_text' => __('&raquo;'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo $paginate_links;
echo "</nav>";
}
}
</code></pre>
<p>I truly need help and advices. Thanks a lot in advance!</p>
|
[
{
"answer_id": 252742,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": -1,
"selected": false,
"text": "<p>Everything looks like things I've used in a similar fashion. The only thing, is, I believe the <code>function_exists</code> parameter <a href=\"http://php.net/manual/en/function.function-exists.php\" rel=\"nofollow noreferrer\">needs to pass a string</a>. It should be:</p>\n\n<pre><code>if ( function_exists('search_pagination') ) {\n</code></pre>\n\n<p>Looks like the way you had it wouldn't register it as a string.</p>\n"
},
{
"answer_id": 252839,
"author": "Jayesh",
"author_id": 98501,
"author_profile": "https://wordpress.stackexchange.com/users/98501",
"pm_score": 2,
"selected": false,
"text": "<p>From your job-search.php replace <code>'posts_per_page' => 10,</code> to <code>'posts_per_page' => 3,</code></p>\n\n<p>and Simply add this following code in your search page, i mean where you are searching the posts.</p>\n\n<pre><code>the_posts_pagination( array( 'mid_size' => 2 ) );\n</code></pre>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252740",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105223/"
] |
I'm building currently a website on WordPress. The site has a custom post type. I have a customized search form, which selects entries from custom post type. Entries are being selected and sorted as they are supposed to, however on my search result page (job-search.php) I need a pagination, and it's not working, although same codes works fine on other pages. I see page number changing in browser's search bar, but I always see entries from first page.
Code for search form and query for custom post type with specified selections and filtering (inside job-search.php):
```
<?php
/*
* Template Name:job-search
*/
get_header();?>
<div>
<form method="get" action="<?php echo site_url('/'); ?>/job-search" >
<input type="search" name="job-name" placeholder="Job..." />
<input type="search" name="town-name" placeholder="Town..." />
<select type="search" name="date">
<option value="DESC">Datum absteigend</option>
<option value="ASC">Datum aufsteigend</option>
</select>
<div>
<input type="checkbox" name="cat[]" value="IT, Telekommunikation" />IT, Telekommunikation
<input type="checkbox" name="cat[]" value="Ingenieur, Technik" />Ingenieur, Technik
<input type="checkbox" name="cat[]" value="Handwerk, Gewerbe" />Handwerk, Gewerbe
</div>
<input type="submit" value="Search">
</form>
</div>
<?php
$jobName = $_GET['job-name'];
$jobTown = $_GET['town-name'];
$jobDate = $_GET['date'];
if($_GET['cat'] && !empty($_GET['cat'])){
$jobCat = $_GET['cat'];
}
else{
$jobCat = array('Vertrieb, Verkauf', 'IT, Telekommunikation', 'Ingenieur, Technik', 'Personalwesen', 'Bildung, Soziales', 'Einkauf, Logistik', 'Handwerk, Gewerbe', 'Führungskräfte', 'Marketing, PR', 'Medizin, Pflege', 'Finanzen, Steuern, Recht', 'Kaufmännische Berufe', 'Luft- und Raumfahrt, Reise', 'Ausbildung', '');
}
?>
<h1 style="font-size:1.5em; font-weight:bold; border-bottom:2px solid green; color:green; margin-bottom:20px;">wp_query_search results</h1>
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$q1 = array(
'post_type' => 'jobs',
's' => $jobName,
'posts_per_page' => 10,
'paged' => $paged,
'meta_key' => 'date',
'orderby' => 'meta_value',
'order' => $jobDate,
'meta_query' => array (
'relation' => 'AND',
array(
'key' => 'town',
'value' => $jobTown,
'compare' => 'LIKE'
),
array(
'relation' => 'OR',
array(
'key' => 'cat_1',
'value' => $jobCat
),
array(
'key' => 'cat_2',
'value' => $jobCat
)
)
)
);
$query = new WP_Query($q1);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post();?>
<h2 style="color:brown; font-weight:bold; border-bottom:1px dotted brown;"><?php the_field('title'); ?></h2>
<h3><?php the_field('town'); ?></h3>
<h4><?php the_field('cat_1'); ?> | <?php the_field('cat_2'); ?></h4>
<h5><?php the_field('date'); ?></h5>
<?php endwhile;
if (function_exists(search_pagination)) {
search_pagination($query->max_num_pages,"",$paged);
}
endif; wp_reset_query(); ?>
</div>
<?php get_footer(); ?>
```
Code for Pagination (inside functions.php):
```
function search_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
$paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
//global $wp_query;
//$numpages = $wp_query->max_num_pages;
$numpages = $query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo $paginate_links;
echo "</nav>";
}
}
```
I truly need help and advices. Thanks a lot in advance!
|
From your job-search.php replace `'posts_per_page' => 10,` to `'posts_per_page' => 3,`
and Simply add this following code in your search page, i mean where you are searching the posts.
```
the_posts_pagination( array( 'mid_size' => 2 ) );
```
|
252,743 |
<p>I have a taxonomy called "location". I'm outputting a comma separated list of these taxonomy terms for a post. This is fine, but I don't know how to split the second-to-last and last items with "and" instead of a comma. </p>
<p>Here is my code. Is there a way to do it using the counter maybe?</p>
<pre><code>$locations = get_the_terms($post->ID, 'location');
$locations = array_values($locations);
for($cat_count=0; $cat_count<count($locations); $cat_count++) {
echo $locations[$cat_count]->name;
if ($cat_count<count($locations)-1){
echo ', ';
}
}
</code></pre>
<p>Note: This code is in the sidebar for a category archive template and inside a WP_Query, so it's all within the loop. The WP_Query is outputting multiple posts of a custom post type called Projects and I'm trying to list the location tax terms for each one. </p>
|
[
{
"answer_id": 252746,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 3,
"selected": true,
"text": "<p>This is how your code should look like I added some comments so you will understand its simple programming not really wordpress related.</p>\n\n<pre><code>$locations = get_the_terms($post->ID, 'location');\n$locations = array_values($locations);\n\n$total_locations = count($locations); // the total start from 1\n\nfor($i = 0; $i < $total_locations; $i++) {\n\n echo $locations[$i]; // echo the location\n\n if($i < $total_locations-2) { // so for comma you need to check if the for loop variable is - 2 because the loop start from 0\n echo ', '; // echo comma\n } elseif($i < $total_locations-1) { // and here is just -1 because you want to print it before the last one because this we use the less than sign in both of our conditions \n echo ' and '; // echo and\n }\n}\n</code></pre>\n"
},
{
"answer_id": 252747,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>You should replace fragment in your code which echoes comma by the following:</p>\n\n<pre><code>if ($cat_count<count($locations)-2) {\n echo ', ';\n}\nif ($cat_count=count($locations)-2) {\n echo 'and ';\n}\n</code></pre>\n\n<p>This will output comma after all elements of array, except last and previous to last elements.</p>\n\n<p>Elements in array have indexes from 0 to \"count ($locations)-1\".</p>\n\n<p>Element previous to last has index count($locations)-2. After this element, code outputs \" and \".</p>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22448/"
] |
I have a taxonomy called "location". I'm outputting a comma separated list of these taxonomy terms for a post. This is fine, but I don't know how to split the second-to-last and last items with "and" instead of a comma.
Here is my code. Is there a way to do it using the counter maybe?
```
$locations = get_the_terms($post->ID, 'location');
$locations = array_values($locations);
for($cat_count=0; $cat_count<count($locations); $cat_count++) {
echo $locations[$cat_count]->name;
if ($cat_count<count($locations)-1){
echo ', ';
}
}
```
Note: This code is in the sidebar for a category archive template and inside a WP\_Query, so it's all within the loop. The WP\_Query is outputting multiple posts of a custom post type called Projects and I'm trying to list the location tax terms for each one.
|
This is how your code should look like I added some comments so you will understand its simple programming not really wordpress related.
```
$locations = get_the_terms($post->ID, 'location');
$locations = array_values($locations);
$total_locations = count($locations); // the total start from 1
for($i = 0; $i < $total_locations; $i++) {
echo $locations[$i]; // echo the location
if($i < $total_locations-2) { // so for comma you need to check if the for loop variable is - 2 because the loop start from 0
echo ', '; // echo comma
} elseif($i < $total_locations-1) { // and here is just -1 because you want to print it before the last one because this we use the less than sign in both of our conditions
echo ' and '; // echo and
}
}
```
|
252,760 |
<p>I am trying to load more content with ajax. the script does not return anything when I am logged out.</p>
<p>this is my php code</p>
<pre><code><?php
function get_blog_items()
{
$offset = (int)intval($_POST['offset']);
$args = array(
'posts_per_page' => 4,
'post_type' => 'post',
'offset' => $offset
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'template-parts/list', 'blog' );
endwhile;
endif;
wp_reset_postdata();
}
function add_ajax_actions() {
add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );
}
add_action( 'admin_init', 'add_ajax_actions' );
</code></pre>
<p>And my javascript</p>
<pre><code>$(document).ready(function($) {
var loadbuttonBlogItems = $('#loadmore-blog-items');
loadbuttonBlogItems.on('click', function() {
$(this).addClass('loading');
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
dataType: 'html',
data: {
action: 'get_blog_items',
offset: $('body > div.page-wrap > section.blog-listing > ul').children().length
},
})
.done(function(data) {
console.log(data);
$('.blog-listing ul').append($.parseHTML(data))
})
.fail(function() {
console.log("error occured while loading more blog items");
})
.always(function() {
console.log("ajax call finished");
$(loadbuttonBlogItems).removeClass('loading');
});
})
});
</code></pre>
|
[
{
"answer_id": 252761,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function add_ajax_actions() {\n add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );\n}\n\nadd_action( 'admin_init', 'add_ajax_actions' );\n</code></pre>\n\n<p><code>admin_init</code> only runs when the admin area is initialised. Logged out people can't access wp-admin, so <code>add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );</code> never runs. Move the add_action call out of that function and remove the <code>add_ajax_actions</code> function and it should work.</p>\n\n<p>Have you considered using the REST API instead?</p>\n"
},
{
"answer_id": 324833,
"author": "RS Dev",
"author_id": 158477,
"author_profile": "https://wordpress.stackexchange.com/users/158477",
"pm_score": 1,
"selected": false,
"text": "<p>Add this for login and logout then Ajax will work for both cases.</p>\n\n<pre><code>if ( is_user_logged_in() ) {\nadd_action( 'wp_ajax_' . $_REQUEST['action'] );\n} else {\nadd_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );\n}\n</code></pre>\n"
}
] |
2017/01/16
|
[
"https://wordpress.stackexchange.com/questions/252760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107702/"
] |
I am trying to load more content with ajax. the script does not return anything when I am logged out.
this is my php code
```
<?php
function get_blog_items()
{
$offset = (int)intval($_POST['offset']);
$args = array(
'posts_per_page' => 4,
'post_type' => 'post',
'offset' => $offset
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'template-parts/list', 'blog' );
endwhile;
endif;
wp_reset_postdata();
}
function add_ajax_actions() {
add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );
}
add_action( 'admin_init', 'add_ajax_actions' );
```
And my javascript
```
$(document).ready(function($) {
var loadbuttonBlogItems = $('#loadmore-blog-items');
loadbuttonBlogItems.on('click', function() {
$(this).addClass('loading');
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
dataType: 'html',
data: {
action: 'get_blog_items',
offset: $('body > div.page-wrap > section.blog-listing > ul').children().length
},
})
.done(function(data) {
console.log(data);
$('.blog-listing ul').append($.parseHTML(data))
})
.fail(function() {
console.log("error occured while loading more blog items");
})
.always(function() {
console.log("ajax call finished");
$(loadbuttonBlogItems).removeClass('loading');
});
})
});
```
|
```
function add_ajax_actions() {
add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );
}
add_action( 'admin_init', 'add_ajax_actions' );
```
`admin_init` only runs when the admin area is initialised. Logged out people can't access wp-admin, so `add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );` never runs. Move the add\_action call out of that function and remove the `add_ajax_actions` function and it should work.
Have you considered using the REST API instead?
|
252,765 |
<p>I plan to bulid up a nice developer environment and for this I need to clone the actual running website to a 100% into a <code>dev</code> directory.</p>
<p>I've now uploaded the same version of wordpress as on my running site and wondering if I could enter the same database and the same prefix as for the running site while running through the installation process. My goal is to connect the development website to the same database, so that it displays the same articles as the running website. Both sites should be in sync in terms of database content!</p>
<p>But I fear that it overwrites everything in my database and that I lose my data (I've got a backup, but I don't want down-time of the real website), so I'm asking you: What will happen if I enter the same details that are used by the running website? Will the development website display all the existing articles or will it overwrite everything in the database?</p>
|
[
{
"answer_id": 252766,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 0,
"selected": false,
"text": "<p>If you production server allows database connection from anywhere - it will connect. but every update you will do in your dev environment, it will affect the production database - very bad idea.</p>\n"
},
{
"answer_id": 252836,
"author": "RobBenz",
"author_id": 85437,
"author_profile": "https://wordpress.stackexchange.com/users/85437",
"pm_score": 2,
"selected": true,
"text": "<p>Based on your question, I am not exactly sure where your local build sits right now. </p>\n\n<p>This answer is assuming you are starting from scratch, but have a copy of a working wordpress website on a live web server, and working on a mac. </p>\n\n<p>You need to install a web server onto your local computer. I am recommending MAMP.\n<a href=\"https://www.mamp.info/en/\" rel=\"nofollow noreferrer\">https://www.mamp.info/en/</a></p>\n\n<p>After getting mamp installed your next step would be to configure the <code>root</code> folder for your web server, we will move forward with the default settings <code>Applications/MAMP/htdocs/</code> </p>\n\n<p>You will then need some sort of FTP client. Filezilla, Cyberduck, etc. login to your production server, and download the entire website ( probably something like <code>public_html/your_site/</code> ) into a new folder withing the MAMP root ie: <code>/Applications/MAMP/htdocs/your_site</code></p>\n\n<p>You will then need to log into a SQL client to download a copy of your wordpress database, depending on your web hosting provider, they should have something called <code>phpmyadmin</code>. you will need to download the entire <code>database.sql</code> file to your local machine, lets say save it to your <code>desktop</code>. </p>\n\n<p>Take a backup too at this point, just in case. </p>\n\n<p>From there you will need to navigate to <code>phpmyadmin</code> through mamp on your local machine, and upload the .sql file to your local SQL database. if you are comfortable with the command prompt, this will work wonders...</p>\n\n<pre><code>/applications/MAMP/library/bin/mysql -u root -p wordpress_db < /Users/you/Desktop/backupDB.sql\n</code></pre>\n\n<p>if not, you can compress and upload, if the db is huge, you might need to break down the structure, & content into two different downloads & uploads, respectively</p>\n\n<p>You will then to run a few SQL queries to change some core options about your wordpress install, ( to configure for local build )</p>\n\n<pre><code>UPDATE wp_options SET option_value=\"http://newdomain.com\" WHERE option_name=\"siteurl\";\nUPDATE wp_options SET option_value=\"http://newdomain.com\" WHERE option_name=\"home\";\nUPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com');\nUPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com');\nUPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com');\n</code></pre>\n\n<p><code>new domain</code> will be something like, <code>localhost/your_site</code></p>\n\n<p>You then need to update your <code>wp-config.php</code> file to pull from the correct database on your local machine. </p>\n\n<pre><code>define( 'DB_NAME', 'wordpress_db' ); // only if you changed db name (don't)\ndefine( 'DB_USER', 'root' );\ndefine( 'DB_PASSWORD', 'root' );\ndefine( 'DB_HOST', 'localhost' );\n</code></pre>\n\n<p>Now, I believe your <code>localhost/your_site</code> should be working, in the event that only the home page is working, and none of the other pages are, you may need to configure your .htaccess file as follows ( at the same root level as <code>wp-config.php</code> )</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /your_site/index.php [L]\n</IfModule>\n</code></pre>\n\n<p>So at this point you will have a exact copy of your live website.... now how to sync? ..... </p>\n\n<p>check out this plugin... <a href=\"https://github.com/wp-sync-db/wp-sync-db\" rel=\"nofollow noreferrer\">https://github.com/wp-sync-db/wp-sync-db</a>\nwill need to install on your live site, and dev site. </p>\n\n<p>Once active it will allow you to pull your live database into your dev database. you will need to configure an <code>api key</code> on your live site, and configure settings to allow for a <code>pull</code> then copy that api key and paste into dev site plugin settings ( <code>tools > migrate-db</code> ) sync once or twice per day. </p>\n\n<p>please note: I do not recommend pushing your local db to your live db. I only ever pull my live db into my local build. </p>\n\n<p>I hope this tutorial worked for you. </p>\n"
}
] |
2017/01/17
|
[
"https://wordpress.stackexchange.com/questions/252765",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93282/"
] |
I plan to bulid up a nice developer environment and for this I need to clone the actual running website to a 100% into a `dev` directory.
I've now uploaded the same version of wordpress as on my running site and wondering if I could enter the same database and the same prefix as for the running site while running through the installation process. My goal is to connect the development website to the same database, so that it displays the same articles as the running website. Both sites should be in sync in terms of database content!
But I fear that it overwrites everything in my database and that I lose my data (I've got a backup, but I don't want down-time of the real website), so I'm asking you: What will happen if I enter the same details that are used by the running website? Will the development website display all the existing articles or will it overwrite everything in the database?
|
Based on your question, I am not exactly sure where your local build sits right now.
This answer is assuming you are starting from scratch, but have a copy of a working wordpress website on a live web server, and working on a mac.
You need to install a web server onto your local computer. I am recommending MAMP.
<https://www.mamp.info/en/>
After getting mamp installed your next step would be to configure the `root` folder for your web server, we will move forward with the default settings `Applications/MAMP/htdocs/`
You will then need some sort of FTP client. Filezilla, Cyberduck, etc. login to your production server, and download the entire website ( probably something like `public_html/your_site/` ) into a new folder withing the MAMP root ie: `/Applications/MAMP/htdocs/your_site`
You will then need to log into a SQL client to download a copy of your wordpress database, depending on your web hosting provider, they should have something called `phpmyadmin`. you will need to download the entire `database.sql` file to your local machine, lets say save it to your `desktop`.
Take a backup too at this point, just in case.
From there you will need to navigate to `phpmyadmin` through mamp on your local machine, and upload the .sql file to your local SQL database. if you are comfortable with the command prompt, this will work wonders...
```
/applications/MAMP/library/bin/mysql -u root -p wordpress_db < /Users/you/Desktop/backupDB.sql
```
if not, you can compress and upload, if the db is huge, you might need to break down the structure, & content into two different downloads & uploads, respectively
You will then to run a few SQL queries to change some core options about your wordpress install, ( to configure for local build )
```
UPDATE wp_options SET option_value="http://newdomain.com" WHERE option_name="siteurl";
UPDATE wp_options SET option_value="http://newdomain.com" WHERE option_name="home";
UPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com');
```
`new domain` will be something like, `localhost/your_site`
You then need to update your `wp-config.php` file to pull from the correct database on your local machine.
```
define( 'DB_NAME', 'wordpress_db' ); // only if you changed db name (don't)
define( 'DB_USER', 'root' );
define( 'DB_PASSWORD', 'root' );
define( 'DB_HOST', 'localhost' );
```
Now, I believe your `localhost/your_site` should be working, in the event that only the home page is working, and none of the other pages are, you may need to configure your .htaccess file as follows ( at the same root level as `wp-config.php` )
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /your_site/index.php [L]
</IfModule>
```
So at this point you will have a exact copy of your live website.... now how to sync? .....
check out this plugin... <https://github.com/wp-sync-db/wp-sync-db>
will need to install on your live site, and dev site.
Once active it will allow you to pull your live database into your dev database. you will need to configure an `api key` on your live site, and configure settings to allow for a `pull` then copy that api key and paste into dev site plugin settings ( `tools > migrate-db` ) sync once or twice per day.
please note: I do not recommend pushing your local db to your live db. I only ever pull my live db into my local build.
I hope this tutorial worked for you.
|
252,774 |
<p>Simple question: I know this can be achieved with a hook somewhere, but I'm having trouble tracking down exactly where I need to look to implement it. Basically, I need to hook into the featured image / thumbnail hook and update the image URL on the fly. Can someone lend a hand on how I might achieve this with the hook system?</p>
<p>I've essentially created a post inheritance plugin whereby an author can create a template and then mass generate new posts that all inherit from this template. These generated posts are fully dynamic in that at runtime in the public view, my plugin fires and checks to see if the active post is template-based. If it is, the plugin grabs the template's content and inserts that into the currently viewed post. This is working great for the title and text replacement already. Now what I need to do is to display a featured image for these posts, again based on the template's featured image. I don't want to actually update these posts in the DB, I simply need to develop it so that when a template calls <code>the_post_thumbnail</code>, my plugin fires and inserts the image automatically. </p>
<p>I hope that clears it up a bit.</p>
|
[
{
"answer_id": 252783,
"author": "Vishal Kumar Sahu",
"author_id": 101300,
"author_profile": "https://wordpress.stackexchange.com/users/101300",
"pm_score": 0,
"selected": false,
"text": "<p>With PHP it is possible... Just create a function which copies your featured image and renames it (same location or different folder) and returns the new URL. I guess you are doing it for SEO thing? You can also take help of GD Library to compress your images.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/19139434/php-move-a-file-into-a-different-folder-on-the-server\">Here</a> is stack help.\nand here is a function I used for like purpose-</p>\n\n<pre><code>function tb_get_image($image_url,$new_url,$upload_folder=\"\"){\n $slug = $new_url;\n $uri = WP_CONTENT_DIR.\"/uploads/\".$upload_folder;\n $folder = WP_CONTENT_URL.\"/uploads/\".$upload_folder; \n\n $localimage = $uri.$slug.\".jpg\"; #GET Extension using PHP_PATHINFO\n $image = $folder.$slug.\".jpg\"; #GET Extension using PHP_PATHINFO\n\n if(file_exists($localimage) && getimagesize($localimage)){\n return $image;\n }else{\n\n ...\n ...\n ...\n CODE YOU WANT TO MODIFY OR MOVE IMAGE\n MAY BE ANOTHER FUNCTION TO DO IT\n ...\n ...\n ...\n ...\n return $image;\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 252785,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>HTML generated by <code>the_post_thumbnail()</code> & <code>get_the_post_thumbnail()</code> can be altered using the <code>post_thumbnail_html</code> filter. This works even when there is no post thumbnail. Example:</p>\n\n<pre><code>/**\n * Filters the post thumbnail HTML.\n *\n * @since 2.9.0\n *\n * @param string $html The post thumbnail HTML.\n * @param int $post_id The post ID.\n * @param string $post_thumbnail_id The post thumbnail ID.\n * @param string|array $size The post thumbnail size. Image size or array of width and height\n * values (in that order). Default 'post-thumbnail'.\n * @param string $attr Query string of attributes.\n */\nfunction wpse_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {\n // Optionally add any logic here for determining what markup to output.\n // $html will be an empty string if there is no post thumbnail.\n $new_html = '<img src=\"https://placekitten.com/g/600/600\" alt=\"kitten\">';\n return $new_html;\n}\nadd_action( 'post_thumbnail_html', 'wpse_post_thumbnail_html', 10, 5 );\n</code></pre>\n\n<p>The above solution requires that the theme is calling <code>the_post_thumbnail()</code>, but it will work when the post does not have a thumbnail associated with it. </p>\n\n<p>Note that the solution above would not work in the example below if the post does not have a thumbnail. Here, the conditional statement prevents <code>has_post_thumbnail()</code> from being called:</p>\n\n<pre><code>// the_post_thumbnail() will only be called if the post has a thumbnail.\nif ( has_post_thumbnail() ) {\n the_post_thumbnail( 'large' );\n}\n</code></pre>\n\n<h2>Alternate technique (alters src value for existing featured images)</h2>\n\n<p>The <code>wp_get_attachment_image_src</code> filter allows for the <code>src</code> of an attachment to be modified. </p>\n\n<p>This powerful filter affects all attachment image src values, so it is necessary to add/remove the callback function attached to <code>wp_get_attachment_image_src</code> based on the desired conditions.</p>\n\n<p>The <code>begin_fetch_post_thumbnail_html</code> and <code>end_fetch_post_thumbnail_html</code> actions are perfect for this.</p>\n\n<p>Here's some example code that changes the featured image based on the post id. You can modify this code to use whatever logic is necessary to determine when the <code>wpse_wp_get_attachment_image_src</code> callback should be added and removed.</p>\n\n<pre><code>/**\n * Fires before fetching the post thumbnail HTML.\n *\n * Provides \"just in time\" filtering of all filters in wp_get_attachment_image().\n *\n * @since 2.9.0\n *\n * @param int $post_id The post ID.\n * @param string $post_thumbnail_id The post thumbnail ID.\n * @param string|array $size The post thumbnail size. Image size or array of width\n * and height values (in that order). Default 'post-thumbnail'.\n */\nfunction wpse_begin_fetch_post_thumbnail_html( $post_id, $post_thumbnail_id, $size ) {\n // For example, if the post id is 1479, we will add our callback to modify the image.\n // You could use whatever logic you need to determine if the filter should be added.\n if ( 1479 === $post_id ) {\n add_filter( 'wp_get_attachment_image_src', 'wpse_wp_get_attachment_image_src', 10, 4 );\n }\n} \nadd_action( 'begin_fetch_post_thumbnail_html', 'wpse_begin_fetch_post_thumbnail_html', 10, 3 );\n\n/**\n * Fires after fetching the post thumbnail HTML.\n *\n * @since 2.9.0\n *\n * @param int $post_id The post ID.\n * @param string $post_thumbnail_id The post thumbnail ID.\n * @param string|array $size The post thumbnail size. Image size or array of width\n * and height values (in that order). Default 'post-thumbnail'.\n */\nfunction wpse_end_fetch_post_thumbnail_html( $post_id, $post_thumbnail_id, $size ) {\n // Now we remove the callback so that it only affects the desired post.\n if ( 1479 === $post_id ) {\n remove_filter( 'wp_get_attachment_image_src', 'wpse_wp_get_attachment_image_src', 10, 4 );\n }\n} \nadd_action( 'end_fetch_post_thumbnail_html', 'wpse_end_fetch_post_thumbnail_html', 10, 3 ); \n\n/**\n * Filters the image src result.\n *\n *\n * @param array|false $image Either array with src, width & height, icon src, or false.\n * @param int $attachment_id Image attachment ID.\n * @param string|array $size Size of image. Image size or array of width and height values\n * (in that order). Default 'thumbnail'.\n * @param bool $icon Whether the image should be treated as an icon. Default false.\n */\nfunction wpse_wp_get_attachment_image_src( $image, $attachment_id, $size, $icon ) {\n $image[0] = 'https://placekitten.com/g/600/600';\n return $image;\n}\n</code></pre>\n"
}
] |
2017/01/17
|
[
"https://wordpress.stackexchange.com/questions/252774",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27041/"
] |
Simple question: I know this can be achieved with a hook somewhere, but I'm having trouble tracking down exactly where I need to look to implement it. Basically, I need to hook into the featured image / thumbnail hook and update the image URL on the fly. Can someone lend a hand on how I might achieve this with the hook system?
I've essentially created a post inheritance plugin whereby an author can create a template and then mass generate new posts that all inherit from this template. These generated posts are fully dynamic in that at runtime in the public view, my plugin fires and checks to see if the active post is template-based. If it is, the plugin grabs the template's content and inserts that into the currently viewed post. This is working great for the title and text replacement already. Now what I need to do is to display a featured image for these posts, again based on the template's featured image. I don't want to actually update these posts in the DB, I simply need to develop it so that when a template calls `the_post_thumbnail`, my plugin fires and inserts the image automatically.
I hope that clears it up a bit.
|
HTML generated by `the_post_thumbnail()` & `get_the_post_thumbnail()` can be altered using the `post_thumbnail_html` filter. This works even when there is no post thumbnail. Example:
```
/**
* Filters the post thumbnail HTML.
*
* @since 2.9.0
*
* @param string $html The post thumbnail HTML.
* @param int $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string|array $size The post thumbnail size. Image size or array of width and height
* values (in that order). Default 'post-thumbnail'.
* @param string $attr Query string of attributes.
*/
function wpse_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
// Optionally add any logic here for determining what markup to output.
// $html will be an empty string if there is no post thumbnail.
$new_html = '<img src="https://placekitten.com/g/600/600" alt="kitten">';
return $new_html;
}
add_action( 'post_thumbnail_html', 'wpse_post_thumbnail_html', 10, 5 );
```
The above solution requires that the theme is calling `the_post_thumbnail()`, but it will work when the post does not have a thumbnail associated with it.
Note that the solution above would not work in the example below if the post does not have a thumbnail. Here, the conditional statement prevents `has_post_thumbnail()` from being called:
```
// the_post_thumbnail() will only be called if the post has a thumbnail.
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'large' );
}
```
Alternate technique (alters src value for existing featured images)
-------------------------------------------------------------------
The `wp_get_attachment_image_src` filter allows for the `src` of an attachment to be modified.
This powerful filter affects all attachment image src values, so it is necessary to add/remove the callback function attached to `wp_get_attachment_image_src` based on the desired conditions.
The `begin_fetch_post_thumbnail_html` and `end_fetch_post_thumbnail_html` actions are perfect for this.
Here's some example code that changes the featured image based on the post id. You can modify this code to use whatever logic is necessary to determine when the `wpse_wp_get_attachment_image_src` callback should be added and removed.
```
/**
* Fires before fetching the post thumbnail HTML.
*
* Provides "just in time" filtering of all filters in wp_get_attachment_image().
*
* @since 2.9.0
*
* @param int $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string|array $size The post thumbnail size. Image size or array of width
* and height values (in that order). Default 'post-thumbnail'.
*/
function wpse_begin_fetch_post_thumbnail_html( $post_id, $post_thumbnail_id, $size ) {
// For example, if the post id is 1479, we will add our callback to modify the image.
// You could use whatever logic you need to determine if the filter should be added.
if ( 1479 === $post_id ) {
add_filter( 'wp_get_attachment_image_src', 'wpse_wp_get_attachment_image_src', 10, 4 );
}
}
add_action( 'begin_fetch_post_thumbnail_html', 'wpse_begin_fetch_post_thumbnail_html', 10, 3 );
/**
* Fires after fetching the post thumbnail HTML.
*
* @since 2.9.0
*
* @param int $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string|array $size The post thumbnail size. Image size or array of width
* and height values (in that order). Default 'post-thumbnail'.
*/
function wpse_end_fetch_post_thumbnail_html( $post_id, $post_thumbnail_id, $size ) {
// Now we remove the callback so that it only affects the desired post.
if ( 1479 === $post_id ) {
remove_filter( 'wp_get_attachment_image_src', 'wpse_wp_get_attachment_image_src', 10, 4 );
}
}
add_action( 'end_fetch_post_thumbnail_html', 'wpse_end_fetch_post_thumbnail_html', 10, 3 );
/**
* Filters the image src result.
*
*
* @param array|false $image Either array with src, width & height, icon src, or false.
* @param int $attachment_id Image attachment ID.
* @param string|array $size Size of image. Image size or array of width and height values
* (in that order). Default 'thumbnail'.
* @param bool $icon Whether the image should be treated as an icon. Default false.
*/
function wpse_wp_get_attachment_image_src( $image, $attachment_id, $size, $icon ) {
$image[0] = 'https://placekitten.com/g/600/600';
return $image;
}
```
|
252,799 |
<p>Is there a way to disable the edit shortcut buttons that was added in WordPress 4.7?</p>
<p>I noticed they have a class <code>customize-partial-edit-shortcut-button</code> and I can add <code>display:none</code> in css but trying to find a solution in php.</p>
<p><a href="https://i.stack.imgur.com/qfJZ2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qfJZ2.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 252800,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": -1,
"selected": false,
"text": "<p>This featured is enabled by just adding theme support feature. Here is the code</p>\n\n<pre><code>add_theme_support( 'customize-selective-refresh-widgets' )\n</code></pre>\n\n<p>You can find this in functions.php file and remove this line of code to disable the feature or you can add a hook to deactivate it like the code below and place that code at the end of functions.php file.</p>\n\n<pre><code>remove_theme_support( 'customize-selective-refresh-widgets' ); \n</code></pre>\n\n<p>This will deactivate the front end edit shortcut support for your theme.</p>\n\n<p><strong>update:</strong></p>\n\n<p>To remove this support from twenty seventeen theme you have to remove that function which is making live edit support and partial refresh section. And for other theme you have to find out that function inside functions.php file. In this case here is the code solution.</p>\n\n<pre><code>remove_action('customize_register', 'twentyseventeen_customize_register' );\n</code></pre>\n\n<p>place this code at the end of functions.php file and you are done.</p>\n"
},
{
"answer_id": 252937,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest way to disable edit shortcuts without unwanted side effects is to no-op override the JS function that generates them in the first place. You can do this from PHP as follows:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function () {\n $js = 'wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};';\n wp_add_inline_script( 'customize-selective-refresh', $js );\n} );\n</code></pre>\n\n<p>This will work for any theme.</p>\n"
}
] |
2017/01/17
|
[
"https://wordpress.stackexchange.com/questions/252799",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111079/"
] |
Is there a way to disable the edit shortcut buttons that was added in WordPress 4.7?
I noticed they have a class `customize-partial-edit-shortcut-button` and I can add `display:none` in css but trying to find a solution in php.
[](https://i.stack.imgur.com/qfJZ2.png)
|
The simplest way to disable edit shortcuts without unwanted side effects is to no-op override the JS function that generates them in the first place. You can do this from PHP as follows:
```
add_action( 'wp_enqueue_scripts', function () {
$js = 'wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};';
wp_add_inline_script( 'customize-selective-refresh', $js );
} );
```
This will work for any theme.
|
252,816 |
<p>I have a rtl.css file for my theme. when i change site language
to Persian (from settings), rtl.css loaded and work properly.But i want to keep in english lanuage and load rtl.css file. How i do it? when language change, what happens?
please help me.
Tnx a lot.</p>
|
[
{
"answer_id": 252800,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": -1,
"selected": false,
"text": "<p>This featured is enabled by just adding theme support feature. Here is the code</p>\n\n<pre><code>add_theme_support( 'customize-selective-refresh-widgets' )\n</code></pre>\n\n<p>You can find this in functions.php file and remove this line of code to disable the feature or you can add a hook to deactivate it like the code below and place that code at the end of functions.php file.</p>\n\n<pre><code>remove_theme_support( 'customize-selective-refresh-widgets' ); \n</code></pre>\n\n<p>This will deactivate the front end edit shortcut support for your theme.</p>\n\n<p><strong>update:</strong></p>\n\n<p>To remove this support from twenty seventeen theme you have to remove that function which is making live edit support and partial refresh section. And for other theme you have to find out that function inside functions.php file. In this case here is the code solution.</p>\n\n<pre><code>remove_action('customize_register', 'twentyseventeen_customize_register' );\n</code></pre>\n\n<p>place this code at the end of functions.php file and you are done.</p>\n"
},
{
"answer_id": 252937,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest way to disable edit shortcuts without unwanted side effects is to no-op override the JS function that generates them in the first place. You can do this from PHP as follows:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function () {\n $js = 'wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};';\n wp_add_inline_script( 'customize-selective-refresh', $js );\n} );\n</code></pre>\n\n<p>This will work for any theme.</p>\n"
}
] |
2017/01/17
|
[
"https://wordpress.stackexchange.com/questions/252816",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111093/"
] |
I have a rtl.css file for my theme. when i change site language
to Persian (from settings), rtl.css loaded and work properly.But i want to keep in english lanuage and load rtl.css file. How i do it? when language change, what happens?
please help me.
Tnx a lot.
|
The simplest way to disable edit shortcuts without unwanted side effects is to no-op override the JS function that generates them in the first place. You can do this from PHP as follows:
```
add_action( 'wp_enqueue_scripts', function () {
$js = 'wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};';
wp_add_inline_script( 'customize-selective-refresh', $js );
} );
```
This will work for any theme.
|
252,825 |
<p>I would like to know the best part of the code to catch a 404 that doesn't match a template.
However at this point I will check for the url string and output my own dynamic html if it matches a pattern. It is DYNAMIC content because there is no content in the wordpress backend for it. So I am looking to echo html and exit if it matches. If not then continue and 404 as normal.</p>
<p>In reference to this question too.
<a href="https://wordpress.stackexchange.com/questions/252289/dynamic-url-generates-dynamic-content/252293">Dynamic URL generates dynamic content</a></p>
<p>TY</p>
|
[
{
"answer_id": 252800,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": -1,
"selected": false,
"text": "<p>This featured is enabled by just adding theme support feature. Here is the code</p>\n\n<pre><code>add_theme_support( 'customize-selective-refresh-widgets' )\n</code></pre>\n\n<p>You can find this in functions.php file and remove this line of code to disable the feature or you can add a hook to deactivate it like the code below and place that code at the end of functions.php file.</p>\n\n<pre><code>remove_theme_support( 'customize-selective-refresh-widgets' ); \n</code></pre>\n\n<p>This will deactivate the front end edit shortcut support for your theme.</p>\n\n<p><strong>update:</strong></p>\n\n<p>To remove this support from twenty seventeen theme you have to remove that function which is making live edit support and partial refresh section. And for other theme you have to find out that function inside functions.php file. In this case here is the code solution.</p>\n\n<pre><code>remove_action('customize_register', 'twentyseventeen_customize_register' );\n</code></pre>\n\n<p>place this code at the end of functions.php file and you are done.</p>\n"
},
{
"answer_id": 252937,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest way to disable edit shortcuts without unwanted side effects is to no-op override the JS function that generates them in the first place. You can do this from PHP as follows:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function () {\n $js = 'wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};';\n wp_add_inline_script( 'customize-selective-refresh', $js );\n} );\n</code></pre>\n\n<p>This will work for any theme.</p>\n"
}
] |
2017/01/17
|
[
"https://wordpress.stackexchange.com/questions/252825",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96548/"
] |
I would like to know the best part of the code to catch a 404 that doesn't match a template.
However at this point I will check for the url string and output my own dynamic html if it matches a pattern. It is DYNAMIC content because there is no content in the wordpress backend for it. So I am looking to echo html and exit if it matches. If not then continue and 404 as normal.
In reference to this question too.
[Dynamic URL generates dynamic content](https://wordpress.stackexchange.com/questions/252289/dynamic-url-generates-dynamic-content/252293)
TY
|
The simplest way to disable edit shortcuts without unwanted side effects is to no-op override the JS function that generates them in the first place. You can do this from PHP as follows:
```
add_action( 'wp_enqueue_scripts', function () {
$js = 'wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};';
wp_add_inline_script( 'customize-selective-refresh', $js );
} );
```
This will work for any theme.
|
252,849 |
<p>I've done numerous WP sites, written my own plugins, run my own server, etc etc.</p>
<p>But I have not seen this before. I just installed a fresh 4.7.1 and installed the <a href="http://www.newsmartwave.net/?theme=porto_wp" rel="nofollow noreferrer">Proto theme</a> and all its plugins.</p>
<p>When I went to add media files, I got:</p>
<pre><code>Maximum upload file size: 2 KB.
</code></pre>
<p>I deactivated all plugins one by one...no dice. My PHP memory limit is set to 256MB for this installation via wp_config.php.</p>
<p>Googling the 2 KB limit turned up no results. </p>
<p>Anyone seen this before or know how to fix this limit?</p>
|
[
{
"answer_id": 252857,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>Three things you need to check.</p>\n\n<p><code>upload_max_filesize</code>, <code>memory_limit</code> and <code>post_max_size</code> in the php.ini configuration file exactly.</p>\n\n<p>All of these three settings limit the maximum size of data that can be submitted and handled by PHP.</p>\n\n<p>Typically <code>post_max_size</code> and <code>memory_limit</code> need to be larger than <code>upload_max_filesize</code>.</p>\n\n<hr>\n\n<p>This is the function in WordPress that defines the constant you saw:</p>\n\n<pre><code>File: wp-includes/media.php\n2843: /**\n2844: * Determines the maximum upload size allowed in php.ini.\n2845: *\n2846: * @since 2.5.0\n2847: *\n2848: * @return int Allowed upload size.\n2849: */\n2850: function wp_max_upload_size() {\n2851: $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );\n2852: $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );\n2853: \n2854: /**\n2855: * Filters the maximum upload size allowed in php.ini.\n2856: *\n2857: * @since 2.5.0\n2858: *\n2859: * @param int $size Max upload size limit in bytes.\n2860: * @param int $u_bytes Maximum upload filesize in bytes.\n2861: * @param int $p_bytes Maximum size of POST data in bytes.\n2862: */\n2863: return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );\n2864: }\n</code></pre>\n"
},
{
"answer_id": 253633,
"author": "user111587",
"author_id": 111587,
"author_profile": "https://wordpress.stackexchange.com/users/111587",
"pm_score": 1,
"selected": false,
"text": "<p>Try to paste this code below in all .htaccess in root of folder :</p>\n\n<pre><code>Options -Indexes\nphp_value upload_max_filesize 1000M\nphp_value post_max_size 1000M\nphp_value max_execution_time 300\nphp_value max_input_vars 1600\n</code></pre>\n"
},
{
"answer_id": 254505,
"author": "decoder88",
"author_id": 28716,
"author_profile": "https://wordpress.stackexchange.com/users/28716",
"pm_score": 0,
"selected": false,
"text": "<p>Had the same issue with new installs this week. You need to set the upload limits on your php.ini, <strong>if you are on a shared server</strong> you need to create a file called <strong>.user.ini</strong> then paste the code below</p>\n\n<pre><code>upload_max_filesize = 64M\npost_max_size = 64M\nmax_execution_time = 300\n</code></pre>\n"
},
{
"answer_id": 254541,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>There is a plugin \"Max Upload Size\" that will let you easily increase the size of uploads. Fairly lightweight. See <a href=\"https://wordpress.org/plugins/upload-max-file-size/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/upload-max-file-size/</a> </p>\n"
}
] |
2017/01/17
|
[
"https://wordpress.stackexchange.com/questions/252849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111117/"
] |
I've done numerous WP sites, written my own plugins, run my own server, etc etc.
But I have not seen this before. I just installed a fresh 4.7.1 and installed the [Proto theme](http://www.newsmartwave.net/?theme=porto_wp) and all its plugins.
When I went to add media files, I got:
```
Maximum upload file size: 2 KB.
```
I deactivated all plugins one by one...no dice. My PHP memory limit is set to 256MB for this installation via wp\_config.php.
Googling the 2 KB limit turned up no results.
Anyone seen this before or know how to fix this limit?
|
Three things you need to check.
`upload_max_filesize`, `memory_limit` and `post_max_size` in the php.ini configuration file exactly.
All of these three settings limit the maximum size of data that can be submitted and handled by PHP.
Typically `post_max_size` and `memory_limit` need to be larger than `upload_max_filesize`.
---
This is the function in WordPress that defines the constant you saw:
```
File: wp-includes/media.php
2843: /**
2844: * Determines the maximum upload size allowed in php.ini.
2845: *
2846: * @since 2.5.0
2847: *
2848: * @return int Allowed upload size.
2849: */
2850: function wp_max_upload_size() {
2851: $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2852: $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2853:
2854: /**
2855: * Filters the maximum upload size allowed in php.ini.
2856: *
2857: * @since 2.5.0
2858: *
2859: * @param int $size Max upload size limit in bytes.
2860: * @param int $u_bytes Maximum upload filesize in bytes.
2861: * @param int $p_bytes Maximum size of POST data in bytes.
2862: */
2863: return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2864: }
```
|
252,865 |
<p>I want to make a custom WP_Query using custom taxonomy terms ID´s.</p>
<p>Example of the term’s ID’s : 19,18,214,226,20</p>
<p>Why does this work:</p>
<pre><code>$query_args = array (
'post_type' => 'works’,
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => array( 19,18,214,226,20 ),
)
),
);
</code></pre>
<p>It shows all items from all taxonomy terms ID’s,</p>
<p>But this doesn’t:</p>
<p><code>$tax = '19,18,214,226,20';</code></p>
<pre><code>$query_args = array (
'post_type' => 'works',
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => array( $tax ),
)
),
);
</code></pre>
<p>Using the variable <code>$tax</code> the query result only shows items the first term ID (19), and ignores all the others.</p>
<p>Why does this happens and how can i use the variable in the tax_query instead of hardcode the ID’s ?</p>
|
[
{
"answer_id": 252868,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 5,
"selected": true,
"text": "<p>It looks like you are making an array with a single string inside.</p>\n\n<p>Check if making $tax into an array before passing it will work:</p>\n\n<pre><code>$tax = array( 19, 18, 214, 226, 20 );\n\n$query_args = array (\n 'post_type' => 'works',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'materials',\n 'field' => 'term_id',\n 'terms' => $tax,\n )\n ),\n);\n</code></pre>\n\n<p>If you need to make an array from a formatted string, you can use the <code>explode</code> PHP function that takes a delimiter and a string, and returns an array, like so:</p>\n\n<pre><code>$tax_string = '19,18,214,226,20';\n$tax_array = explode( ',', $tax_string );\n</code></pre>\n\n<p>Hope that works!</p>\n"
},
{
"answer_id": 252869,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": 0,
"selected": false,
"text": "<p>Because in php, <code>$tax = '19,18,214,226,20';</code> is a string. and you can't wrap a string within <code>array()</code> and create an array :) </p>\n\n<p>You may need something like : </p>\n\n<pre><code>function comma_separated_to_array($string, $separator = ',')\n{\n //Explode on comma\n $vals = explode($separator, $string);\n\n //Trim whitespace\n foreach($vals as $key => $val) {\n $vals[$key] = trim($val);\n }\n //Return empty array if no items found\n //http://php.net/manual/en/function.explode.php#114273\n return array_diff($vals, array(\"\"));\n}\n</code></pre>\n\n<p>and use it as </p>\n\n<pre><code>$terms= comma_separated_to_array($tax);\n</code></pre>\n"
}
] |
2017/01/17
|
[
"https://wordpress.stackexchange.com/questions/252865",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16324/"
] |
I want to make a custom WP\_Query using custom taxonomy terms ID´s.
Example of the term’s ID’s : 19,18,214,226,20
Why does this work:
```
$query_args = array (
'post_type' => 'works’,
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => array( 19,18,214,226,20 ),
)
),
);
```
It shows all items from all taxonomy terms ID’s,
But this doesn’t:
`$tax = '19,18,214,226,20';`
```
$query_args = array (
'post_type' => 'works',
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => array( $tax ),
)
),
);
```
Using the variable `$tax` the query result only shows items the first term ID (19), and ignores all the others.
Why does this happens and how can i use the variable in the tax\_query instead of hardcode the ID’s ?
|
It looks like you are making an array with a single string inside.
Check if making $tax into an array before passing it will work:
```
$tax = array( 19, 18, 214, 226, 20 );
$query_args = array (
'post_type' => 'works',
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => $tax,
)
),
);
```
If you need to make an array from a formatted string, you can use the `explode` PHP function that takes a delimiter and a string, and returns an array, like so:
```
$tax_string = '19,18,214,226,20';
$tax_array = explode( ',', $tax_string );
```
Hope that works!
|
252,877 |
<p>I've created a new custom post type called <code>doctors</code>. I've been using ACF and pulling these fields to help create my banner. I was wondering what a post would look like if no fields were filled out, so I created a second test post, but I noticed it has all of the same content as my first post.</p>
<p>I feel like I'm writing my function incorrectly, obviously.</p>
<pre><code>function doctor_banner_shortcode() {
$args = array(
'posts_per_page' => 1,
'post_type' => 'doctors',
'post_status' => 'publish'
);
$doctors_query = new WP_Query( $args );
if ( $doctors_query->have_posts() ) :
while ( $doctors_query->have_posts() ) :
$doctors_query->the_post();
$dr_name = get_field( 'practitioner_name' );
$dr_degree = get_field( 'practitioner_title' );
$dr_bio = get_field( 'practitioner_short_bio' );
$dr_cv = get_field( 'practitioner_cv' );
$html_out = '<h1>Dr. ' . $dr_name . '</h1>
<h3">' . $dr_degree . '</h3>
<p>' . $dr_bio . '</p>
<a href="' . $dr_cv . '">' . 'Read CV' . '</a>';
endwhile;
else : // No results
$html_out = "No Doctors Found.";
endif;
wp_reset_query();
return $html_out;
}
add_shortcode( 'doctor_banner', 'doctor_banner_shortcode' );
</code></pre>
<p>Somehow, I think, it's not reading the proper ID of that post to output the correct data. I have two links for my two posts <a href="http://www.ankitdesigns.com/demo/hu/doctors/kevin-kwan/" rel="nofollow noreferrer">here</a> and <a href="http://www.ankitdesigns.com/demo/hu/doctors/test-doctor/" rel="nofollow noreferrer">here</a>.</p>
|
[
{
"answer_id": 252881,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you are not supplying the ID into the loop, forcing it to get the first item chronologically (which is always going to be the latest, regardless of where you call the shortcode).</p>\n\n<p>If your shorcode runs inside <code>the_content</code> you don't even have to run another loop, just use the get_field directly.</p>\n\n<pre><code>function doctor_banner_shortcode() {\n\n $dr_name = get_field( 'practitioner_name' );\n $dr_degree = get_field( 'practitioner_title' );\n $dr_bio = get_field( 'practitioner_short_bio' );\n $dr_cv = get_field( 'practitioner_cv' );\n\n $html_out = '<h1>Dr. ' . $dr_name . '</h1>\n <h3\">' . $dr_degree . '</h3>\n <p>' . $dr_bio . '</p>\n <a href=\"' . $dr_cv . '\">' . 'Read CV' . '</a>';\n\n return $html_out;\n}\n</code></pre>\n\n<p>Lemme know if it works!</p>\n"
},
{
"answer_id": 252883,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>You are querying the entire posts of <code>doctors</code> type, and setting the number of posts per page to one. This will obviously always return the same post.</p>\n\n<p>You need to either set the id of the post, or navigate through the loop to find a match. If you are calling this function in single post page, to filter the results based on post id, you should use the function this way:</p>\n\n<pre><code>function doctor_banner_shortcode($doctor_id) {\n$args = array(\n 'posts_per_page' => 1,\n 'post_type' => 'doctors',\n 'post_status' => 'publish',\n 'p' => $doctor_id\n);\n$doctors_query = new WP_Query( $args );\nif ( $doctors_query->have_posts() ) :\n while ( $doctors_query->have_posts() ) :\n $doctors_query->the_post();\n\n $dr_name = get_field( 'practitioner_name' );\n $dr_degree = get_field( 'practitioner_title' );\n $dr_bio = get_field( 'practitioner_short_bio' );\n $dr_cv = get_field( 'practitioner_cv' );\n\n $html_out = '<h1>Dr. ' . $dr_name . '</h1>\n <h3\">' . $dr_degree . '</h3>\n <p>' . $dr_bio . '</p>\n <a href=\"' . $dr_cv . '\">' . 'Read CV' . '</a>';\n endwhile;\nelse : // No results\n $html_out = \"No Doctors Found.\";\nendif;\nwp_reset_query();\nreturn $html_out;\n}\n\nadd_shortcode( 'doctor_banner', 'doctor_banner_shortcode' );\n</code></pre>\n\n<p>Then you can call your function in the <code>single.php</code> template in this way :\n<code>function doctor_banner_shortcode($post->ID)</code></p>\n\n<p>If you want to call the function manually in some other page, you should set the ID while calling the function.</p>\n"
}
] |
2017/01/17
|
[
"https://wordpress.stackexchange.com/questions/252877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96257/"
] |
I've created a new custom post type called `doctors`. I've been using ACF and pulling these fields to help create my banner. I was wondering what a post would look like if no fields were filled out, so I created a second test post, but I noticed it has all of the same content as my first post.
I feel like I'm writing my function incorrectly, obviously.
```
function doctor_banner_shortcode() {
$args = array(
'posts_per_page' => 1,
'post_type' => 'doctors',
'post_status' => 'publish'
);
$doctors_query = new WP_Query( $args );
if ( $doctors_query->have_posts() ) :
while ( $doctors_query->have_posts() ) :
$doctors_query->the_post();
$dr_name = get_field( 'practitioner_name' );
$dr_degree = get_field( 'practitioner_title' );
$dr_bio = get_field( 'practitioner_short_bio' );
$dr_cv = get_field( 'practitioner_cv' );
$html_out = '<h1>Dr. ' . $dr_name . '</h1>
<h3">' . $dr_degree . '</h3>
<p>' . $dr_bio . '</p>
<a href="' . $dr_cv . '">' . 'Read CV' . '</a>';
endwhile;
else : // No results
$html_out = "No Doctors Found.";
endif;
wp_reset_query();
return $html_out;
}
add_shortcode( 'doctor_banner', 'doctor_banner_shortcode' );
```
Somehow, I think, it's not reading the proper ID of that post to output the correct data. I have two links for my two posts [here](http://www.ankitdesigns.com/demo/hu/doctors/kevin-kwan/) and [here](http://www.ankitdesigns.com/demo/hu/doctors/test-doctor/).
|
You are querying the entire posts of `doctors` type, and setting the number of posts per page to one. This will obviously always return the same post.
You need to either set the id of the post, or navigate through the loop to find a match. If you are calling this function in single post page, to filter the results based on post id, you should use the function this way:
```
function doctor_banner_shortcode($doctor_id) {
$args = array(
'posts_per_page' => 1,
'post_type' => 'doctors',
'post_status' => 'publish',
'p' => $doctor_id
);
$doctors_query = new WP_Query( $args );
if ( $doctors_query->have_posts() ) :
while ( $doctors_query->have_posts() ) :
$doctors_query->the_post();
$dr_name = get_field( 'practitioner_name' );
$dr_degree = get_field( 'practitioner_title' );
$dr_bio = get_field( 'practitioner_short_bio' );
$dr_cv = get_field( 'practitioner_cv' );
$html_out = '<h1>Dr. ' . $dr_name . '</h1>
<h3">' . $dr_degree . '</h3>
<p>' . $dr_bio . '</p>
<a href="' . $dr_cv . '">' . 'Read CV' . '</a>';
endwhile;
else : // No results
$html_out = "No Doctors Found.";
endif;
wp_reset_query();
return $html_out;
}
add_shortcode( 'doctor_banner', 'doctor_banner_shortcode' );
```
Then you can call your function in the `single.php` template in this way :
`function doctor_banner_shortcode($post->ID)`
If you want to call the function manually in some other page, you should set the ID while calling the function.
|
252,920 |
<p>I want to change the default WordPress author link (which is /author/user_nicename) to/author/user_id.</p>
<p>And I found it's easy to do that, I achieved this in two ways:</p>
<p>1.I just copy the <code>get_author_posts_url()</code> function from <code>wp-includes/author-template.php</code> and rewrite it in my theme:</p>
<pre><code>function ji_get_user_url($author_id, $author_nicename = '') {
global $wp_rewrite;
$auth_ID = (int) $author_id;
$link = $wp_rewrite->get_author_permastruct();
if ( empty($link) ) {
$file = home_url( '/' );
$link = $file . '?author=' . $auth_ID;
}else {
if ( '' == $author_nicename ) {
$user = get_userdata($author_id);
if ( !empty($user->user_nicename) )
$author_nicename = $author_id;
}
$link = str_replace('%author%', $author_id, $link);
$link = home_url( user_trailingslashit( $link ) );
}
$link = apply_filters( 'author_link', $link, $author_id, $author_nicename );
return $link;
}
</code></pre>
<p>2.I used the filter:</p>
<pre><code>function chang_author_link($link,$author_id,$author_nicename){
$user_info = get_userdata(get_current_user_id());
$user_id= $user_info->ID;
$link = str_replace($author_nicename, $user_id, $link);
return $link;
}
add_filter('author_link', 'chang_author_link',10,3);
</code></pre>
<p>Either way above can successfully change the default author link to /author/user_id, but that they all returned a 404 not found page! </p>
<p>What happened?</p>
|
[
{
"answer_id": 252899,
"author": "fatwombat",
"author_id": 81482,
"author_profile": "https://wordpress.stackexchange.com/users/81482",
"pm_score": 1,
"selected": false,
"text": "<p>I am doing the same thing at the moment and I just use the standard WP login/register systems/pages.</p>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/wp_signon/\" rel=\"nofollow noreferrer\">wp_signon()</a> to do logon.</p>\n\n<p>Then on a standard page, you can create a custom template and use this for retrieving their info: <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"nofollow noreferrer\">wp_get_current_user()</a></p>\n\n<p>You will also need to get the customer user meta information you store too using: <a href=\"https://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow noreferrer\">get_user_meta()</a></p>\n\n<p>Hope that helps you :)</p>\n"
},
{
"answer_id": 363916,
"author": "hossein naghneh",
"author_id": 175073,
"author_profile": "https://wordpress.stackexchange.com/users/175073",
"pm_score": 0,
"selected": false,
"text": "<p>for find out and init actions </p>\n\n<pre><code>if (!is_user_logged_in()) {\n add_action('init', 'ajax_login_init');\n} else {\n add_action('init', 'ajax_logout_init');\n}\nfunction ajax_login_init()\n{\n add_action('wp_ajax_nopriv_ajax_login', 'ajax_login');\n add_action('wp_ajax_nopriv_ajax_register', 'ajax_register');\n}\nfunction ajax_logout_init()\n{\n add_action('wp_ajax_ajax_logout', 'ajax_logout');\n}\n</code></pre>\n\n<p>login function</p>\n\n<pre><code>function ajax_login()\n{\n check_ajax_referer('ajax-login-nonce', 'security');\n $info = array();\n $info['user_login'] = $_POST['login_username'];\n $info['user_password'] = $_POST['login_password'];\n $info['remember'] = $_POST['remember'];\n\n $user_signon = wp_signon($info, false);\n if (is_wp_error($user_signon)) {\n wp_send_json(array('status' => 0, 'message' => $user_signon->get_error_message()));\n } else {\n wp_send_json(array('status' => 1, 'message' => __('you currectly logined')));;\n }\n}\n</code></pre>\n\n<p>register function</p>\n\n<pre><code>function ajax_register()\n{\n check_ajax_referer('ajax-register-nonce', 'security');\n // Post values\n $username = sanitize_text_field($_POST['register_username']);\n $password = sanitize_text_field($_POST['register_password']);\n $email = sanitize_text_field($_POST['register_email']);\n $name = sanitize_text_field($_POST['register_name']);\n $nick = sanitize_text_field($_POST['register_name']);\n\n $userdata = array(\n 'user_login' => $username,\n 'user_pass' => $password,\n 'user_password' => $password,\n 'user_email' => $email,\n 'first_name' => $name,\n 'nickname' => $nick,\n );\n\n $user_id = wp_insert_user($userdata);\n\n // add user meta\n $custom_user_meta_value = 'custom_user_meta_value';\n add_user_meta( $user_id, 'custom_user_meta', $custom_user_meta_value);\n\n // Return\n if (!is_wp_error($user_id)) {\n $user_signon = wp_signon($userdata, false);\n if (!is_wp_error($user_signon)) {\n wp_send_json(array('status' => 2, 'message' => __('your registration is successfuled and logined.')));\n } else {\n wp_send_json(array('status' => 1, 'message' => __('your registration is successfuled and logined')));\n }\n } else {\n wp_send_json(array('status' => 0, 'message' => __($user_id->get_error_message())));\n }\n}\n</code></pre>\n\n<p>logout function </p>\n\n<pre><code>function ajax_logout()\n{\n check_ajax_referer('ajax-logout-nonce', 'ajaxsecurity');\n\n wp_logout();\n ob_clean(); // probably overkill for this, but good habit\n echo 'adios!!';\n wp_die();\n}\n\nadd_action('wp_logout', 'auto_redirect_after_logout');\nfunction auto_redirect_after_logout()\n{\n wp_redirect(home_url());\n exit();\n}\n</code></pre>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/252920",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105000/"
] |
I want to change the default WordPress author link (which is /author/user\_nicename) to/author/user\_id.
And I found it's easy to do that, I achieved this in two ways:
1.I just copy the `get_author_posts_url()` function from `wp-includes/author-template.php` and rewrite it in my theme:
```
function ji_get_user_url($author_id, $author_nicename = '') {
global $wp_rewrite;
$auth_ID = (int) $author_id;
$link = $wp_rewrite->get_author_permastruct();
if ( empty($link) ) {
$file = home_url( '/' );
$link = $file . '?author=' . $auth_ID;
}else {
if ( '' == $author_nicename ) {
$user = get_userdata($author_id);
if ( !empty($user->user_nicename) )
$author_nicename = $author_id;
}
$link = str_replace('%author%', $author_id, $link);
$link = home_url( user_trailingslashit( $link ) );
}
$link = apply_filters( 'author_link', $link, $author_id, $author_nicename );
return $link;
}
```
2.I used the filter:
```
function chang_author_link($link,$author_id,$author_nicename){
$user_info = get_userdata(get_current_user_id());
$user_id= $user_info->ID;
$link = str_replace($author_nicename, $user_id, $link);
return $link;
}
add_filter('author_link', 'chang_author_link',10,3);
```
Either way above can successfully change the default author link to /author/user\_id, but that they all returned a 404 not found page!
What happened?
|
I am doing the same thing at the moment and I just use the standard WP login/register systems/pages.
You can use [wp\_signon()](https://developer.wordpress.org/reference/functions/wp_signon/) to do logon.
Then on a standard page, you can create a custom template and use this for retrieving their info: [wp\_get\_current\_user()](https://codex.wordpress.org/Function_Reference/wp_get_current_user)
You will also need to get the customer user meta information you store too using: [get\_user\_meta()](https://codex.wordpress.org/Function_Reference/get_user_meta)
Hope that helps you :)
|
252,922 |
<p>Why is it that when I attempt to change the URL for searches, it breaks if set to anything other than <code>search</code>?</p>
<pre><code>function bfm_pretty_search () {
if (is_search() && !empty($_GET['s'])) {
wp_redirect(home_url('/search/').urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'bfm_pretty_search');
</code></pre>
<p>So, instead of the url looking like <code>mydomain.com/search/query</code>, I'd like it to be: <code>mydomain.com/results/query</code>, but it doesn't work with anything other than "search"... why?</p>
|
[
{
"answer_id": 252924,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>To change the search url hook in this function this will replace \"search\" to whatever you want.</p>\n\n<pre><code>add_action( 'init', 'wpse21549_init' );\nfunction wpse21549_init()\n{\n $GLOBALS['wp_rewrite']->search_base = 'results';\n}\n</code></pre>\n\n<p>place this code in your functions.php file and after saving this file. Go to permalink settings page and click on the save button to flush the rewrite rules.</p>\n\n<p><strong>update</strong></p>\n\n<p>To modify the search rewrite rules you can hook into the search_rewrite_rules filter. You can either add the extra rewrite rules that match post types yourself, or you can change the default \"search rewrite structure\" to also include the post type and then re-generate the rules (there are four rules: one standard, one with paging and two for feeds).</p>\n\n<pre><code>add_filter( 'search_rewrite_rules', 'wpse15418_search_rewrite_rules' );\nfunction wpse15418_search_rewrite_rules( $search_rewrite_rules )\n{\n global $wp_rewrite;\n $wp_rewrite->add_rewrite_tag( '%post_type%', '([^/]+)', 'post_type=' );\n $search_structure = $wp_rewrite->get_search_permastruct();\n return $wp_rewrite->generate_rewrite_rules( $search_structure . '/section/%post_type%', EP_SEARCH );\n}\n</code></pre>\n"
},
{
"answer_id": 390953,
"author": "davey",
"author_id": 128873,
"author_profile": "https://wordpress.stackexchange.com/users/128873",
"pm_score": 0,
"selected": false,
"text": "<p>None of the above worked for me. Found another solution by overwriting the search rewrite rules using the search_rewrite_rules filter.</p>\n<p>1 - Add this to the functions.php of your theme:</p>\n<pre><code>add_filter( 'search_rewrite_rules', function($rules) {\n \n $new_rules = [];\n\n // New search slug here\n $new_search_slug = 'zoeken';\n \n foreach ($rules AS $key => $value){\n \n $new_rules[str_replace('search', $new_search_slug, $key)] = $value;\n \n }\n\n return $new_rules;\n\n});\n</code></pre>\n<p>2 - Save the permalinks in the WordPress admin under Settings -> Permalinks.</p>\n<p>Now the page <a href=\"https://www.mywebsite.com/zoeken/searchterm\" rel=\"nofollow noreferrer\">https://www.mywebsite.com/zoeken/searchterm</a> is showing the search results page.</p>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/252922",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25735/"
] |
Why is it that when I attempt to change the URL for searches, it breaks if set to anything other than `search`?
```
function bfm_pretty_search () {
if (is_search() && !empty($_GET['s'])) {
wp_redirect(home_url('/search/').urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'bfm_pretty_search');
```
So, instead of the url looking like `mydomain.com/search/query`, I'd like it to be: `mydomain.com/results/query`, but it doesn't work with anything other than "search"... why?
|
To change the search url hook in this function this will replace "search" to whatever you want.
```
add_action( 'init', 'wpse21549_init' );
function wpse21549_init()
{
$GLOBALS['wp_rewrite']->search_base = 'results';
}
```
place this code in your functions.php file and after saving this file. Go to permalink settings page and click on the save button to flush the rewrite rules.
**update**
To modify the search rewrite rules you can hook into the search\_rewrite\_rules filter. You can either add the extra rewrite rules that match post types yourself, or you can change the default "search rewrite structure" to also include the post type and then re-generate the rules (there are four rules: one standard, one with paging and two for feeds).
```
add_filter( 'search_rewrite_rules', 'wpse15418_search_rewrite_rules' );
function wpse15418_search_rewrite_rules( $search_rewrite_rules )
{
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag( '%post_type%', '([^/]+)', 'post_type=' );
$search_structure = $wp_rewrite->get_search_permastruct();
return $wp_rewrite->generate_rewrite_rules( $search_structure . '/section/%post_type%', EP_SEARCH );
}
```
|
252,925 |
<p>For the homepage, I'd like the main page background to be the background for the entire page, including the footer.</p>
<p>Please help!?</p>
<p>Reed</p>
<p><a href="https://i.stack.imgur.com/4YifW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4YifW.jpg" alt="enter image description here"></a></p>
|
[
{
"answer_id": 252928,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 1,
"selected": false,
"text": "<p>It's better if you share the the link to your site OR if you can show us the attempts you have made and the problems which your are facing while doing so. </p>\n\n<p>A suggestion for to do so is to make footer background transparent and apply background image to your .page class which is default wordpress class you can be more specific with by using unique page ID in css and then apply that background.\nfor example:</p>\n\n<pre><code>#example-pageid footer {\n background:transparent;\n }\n\n#example-pageid {\n background_image:url(your/image/\n }\n</code></pre>\n"
},
{
"answer_id": 252930,
"author": "Faisal Alvi",
"author_id": 73262,
"author_profile": "https://wordpress.stackexchange.com/users/73262",
"pm_score": 0,
"selected": false,
"text": "<p><strong>UPDATE</strong></p>\n\n<p>Add following code to the bottom of your <strong>avada-1035.css</strong> (<a href=\"http://www.chollimacoffee.co/wp-content/uploads/avada-styles/avada-1035.css\" rel=\"nofollow noreferrer\">here is the path</a>):</p>\n\n<pre><code>#wrapper {\n background-image: url(../2016/12/Green-Background-PC-Free-Download.jpg);\n}\n</code></pre>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/252925",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111160/"
] |
For the homepage, I'd like the main page background to be the background for the entire page, including the footer.
Please help!?
Reed
[](https://i.stack.imgur.com/4YifW.jpg)
|
It's better if you share the the link to your site OR if you can show us the attempts you have made and the problems which your are facing while doing so.
A suggestion for to do so is to make footer background transparent and apply background image to your .page class which is default wordpress class you can be more specific with by using unique page ID in css and then apply that background.
for example:
```
#example-pageid footer {
background:transparent;
}
#example-pageid {
background_image:url(your/image/
}
```
|
252,947 |
<p>I have wordpress template from themeforest and I would like to set it up, just like demo page on themeforest....</p>
<p>I found files like customizer.dat.txt, demo=content.xml, widgets.json ...</p>
<p>they probably serve for this purpose but as I'm newbie in Wordpress, have no idea how to use them.</p>
<p>Can you please help me how to import ? Thank you so much!</p>
|
[
{
"answer_id": 252928,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 1,
"selected": false,
"text": "<p>It's better if you share the the link to your site OR if you can show us the attempts you have made and the problems which your are facing while doing so. </p>\n\n<p>A suggestion for to do so is to make footer background transparent and apply background image to your .page class which is default wordpress class you can be more specific with by using unique page ID in css and then apply that background.\nfor example:</p>\n\n<pre><code>#example-pageid footer {\n background:transparent;\n }\n\n#example-pageid {\n background_image:url(your/image/\n }\n</code></pre>\n"
},
{
"answer_id": 252930,
"author": "Faisal Alvi",
"author_id": 73262,
"author_profile": "https://wordpress.stackexchange.com/users/73262",
"pm_score": 0,
"selected": false,
"text": "<p><strong>UPDATE</strong></p>\n\n<p>Add following code to the bottom of your <strong>avada-1035.css</strong> (<a href=\"http://www.chollimacoffee.co/wp-content/uploads/avada-styles/avada-1035.css\" rel=\"nofollow noreferrer\">here is the path</a>):</p>\n\n<pre><code>#wrapper {\n background-image: url(../2016/12/Green-Background-PC-Free-Download.jpg);\n}\n</code></pre>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/252947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111175/"
] |
I have wordpress template from themeforest and I would like to set it up, just like demo page on themeforest....
I found files like customizer.dat.txt, demo=content.xml, widgets.json ...
they probably serve for this purpose but as I'm newbie in Wordpress, have no idea how to use them.
Can you please help me how to import ? Thank you so much!
|
It's better if you share the the link to your site OR if you can show us the attempts you have made and the problems which your are facing while doing so.
A suggestion for to do so is to make footer background transparent and apply background image to your .page class which is default wordpress class you can be more specific with by using unique page ID in css and then apply that background.
for example:
```
#example-pageid footer {
background:transparent;
}
#example-pageid {
background_image:url(your/image/
}
```
|
252,951 |
<p>how to insert data in wordpress using jquery ajax for my plugin, i tried a lot but my action.php page not access global $wpdb, Please tell me where is the problem.</p>
<p>Here is the code of my submenu page of plugin</p>
<pre><code><?php
function pincode()
{
?>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&id='+id;
}
$.ajax({
type: 'POST',
//url: 'http://localhost/wordpress/wp-content/plugins/arunkumar/action.php',
url : '<?php echo plugin_dir_url(__FILE__).'action.php';?>',
data: userData,
success:function(msg){
if(msg == 'ok'){
alert('User data has been '+statusArr[type]+' successfully.');
//getUsers();
$('.form')[0].reset();
$('.formData').slideUp();
}else{
//alert('Some problem occurred, please try again.');
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+msg+' !</div>');
}
}
});
}
</script>
<div class="panel-heading">States <a href="javascript:void(0);" class="glyphicon glyphicon-plus" id="addLink" onclick="javascript:$('#addForm').slideToggle();"></a></div>
<div class="panel-body none formData" id="addForm">
<h2 id="actionLabel">Add New State</h2>
<form class="form" id="userForm">
<div id="error"></div>
<div class="form-group">
<label>State Name</label>
<input type="text" class="form-control" placeholder="Enter State Name" name="name" id="name"/>
</div>
<a href="javascript:void(0);" class="btn btn-warning" onclick="$('#addForm').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add State</a>
</form>
</div>
<?php
}
</code></pre>
<p>and this is action.php code where insert code is applied but it show " Fatal error: Call to a member function insert() on null " error</p>
<pre><code> <?php
if(isset($_POST['action_type']) && !empty($_POST['action_type'])){
if($_POST['action_type'] == 'add'){
//echo $insert?'ok':'err';
global $wpdb;
$state_name = $_POST['name'];
$wpdb->insert( 'state',array( 'state_name' => $state_n),array('%s') );
$status = $wpdb->insert_id;
echo $status ? 'ok' : var_dump($wpdb);
}
</code></pre>
|
[
{
"answer_id": 252957,
"author": "Ravi Shinde",
"author_id": 99294,
"author_profile": "https://wordpress.stackexchange.com/users/99294",
"pm_score": 2,
"selected": false,
"text": "<p>The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>I have tried this and it works well. </p>\n"
},
{
"answer_id": 253003,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 1,
"selected": false,
"text": "<p>looks like Ravi Shinde is right:</p>\n\n<blockquote>\n <p>The code you have shared can work in core PHP and not in Wordpress.\n Using AJAX in Wordpress plugin is explained in Wordpress\n documentation. Please refer -\n <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n</blockquote>\n\n<p>To give your plugin access to the ajax interface you need to wrap it around WordPress' AJAX action <code>wp_ajax_{action}</code></p>\n\n<p>First, you need to define the action:</p>\n\n<pre><code>add_action( 'wp_ajax_user_action', 'user_action' );\nadd_action( 'wp_ajax_nopriv_user_action', 'user_action' );\n</code></pre>\n\n<p>Which registers the <code>user_action</code> with wordpress for both logged in and not authenticated users.</p>\n\n<p>Then you build your handling function:</p>\n\n<pre><code>function user_action() {\n // since this gets loaded by wordpress\n // you get access to $wpdb and other\n // core functions\n global $wpdb; \n\n $state_name = $_POST['name']; \n\n $wpdb->insert( 'state',array( 'state_name' => $state_n),array('%s') );\n $status = $wpdb->insert_id;\n\n echo $status ? 'ok' : var_dump($wpdb);\n\n // Ajax calls in WP always need to be closed with wp_die:\n wp_die(); \n}\n</code></pre>\n\n<p>Finally, you need to get a reference the endpoint ( wordpress shares a single URL for all ajax calls ). In your JS:</p>\n\n<pre><code>var ajaxurl = <?php echo admin_url( 'admin-ajax.php' ); ?>;\n</code></pre>\n\n<p>Note: The \"correct\" way to register scripts is through <code>enqueue_scripts</code>, but thats beyond our scope right now.</p>\n\n<p>Then you can do a regular Ajax call to <code>ajaxurl</code> and passing <code>{ action: 'user_action' }</code> as data.</p>\n\n<p>Truth be told its not the best way, but you get used to it. If you need a primer, Smashinmag always has great articles: </p>\n\n<p><a href=\"https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/</a></p>\n\n<p>( Also: I haven't tested the code but is pretty standard and should work out of the box. Lemme know! )</p>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/252951",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110592/"
] |
how to insert data in wordpress using jquery ajax for my plugin, i tried a lot but my action.php page not access global $wpdb, Please tell me where is the problem.
Here is the code of my submenu page of plugin
```
<?php
function pincode()
{
?>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&id='+id;
}
$.ajax({
type: 'POST',
//url: 'http://localhost/wordpress/wp-content/plugins/arunkumar/action.php',
url : '<?php echo plugin_dir_url(__FILE__).'action.php';?>',
data: userData,
success:function(msg){
if(msg == 'ok'){
alert('User data has been '+statusArr[type]+' successfully.');
//getUsers();
$('.form')[0].reset();
$('.formData').slideUp();
}else{
//alert('Some problem occurred, please try again.');
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+msg+' !</div>');
}
}
});
}
</script>
<div class="panel-heading">States <a href="javascript:void(0);" class="glyphicon glyphicon-plus" id="addLink" onclick="javascript:$('#addForm').slideToggle();"></a></div>
<div class="panel-body none formData" id="addForm">
<h2 id="actionLabel">Add New State</h2>
<form class="form" id="userForm">
<div id="error"></div>
<div class="form-group">
<label>State Name</label>
<input type="text" class="form-control" placeholder="Enter State Name" name="name" id="name"/>
</div>
<a href="javascript:void(0);" class="btn btn-warning" onclick="$('#addForm').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add State</a>
</form>
</div>
<?php
}
```
and this is action.php code where insert code is applied but it show " Fatal error: Call to a member function insert() on null " error
```
<?php
if(isset($_POST['action_type']) && !empty($_POST['action_type'])){
if($_POST['action_type'] == 'add'){
//echo $insert?'ok':'err';
global $wpdb;
$state_name = $_POST['name'];
$wpdb->insert( 'state',array( 'state_name' => $state_n),array('%s') );
$status = $wpdb->insert_id;
echo $status ? 'ok' : var_dump($wpdb);
}
```
|
The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - <https://codex.wordpress.org/AJAX_in_Plugins>
I have tried this and it works well.
|
252,963 |
<p>How to make this query more simplest and in one query? </p>
<p>Problem - only topics has a meta_key 'include_newsletter_feed'<br>
So i need get all posts ("product", "post", "page") excluding categories (124, 52)<br>
And join all topics with meta. </p>
<p>Example ugly code</p>
<pre><code>$arg = array(
"post_type" => array("product", "post", "page"),
"posts_per_page" => 3,
'category__not_in' => array( 124 /*Gallery*/, 52 /* Discounts */ )
);
$_posts = get_posts($arg);
$arg = array(
"post_type" => "topic",
"posts_per_page" => $nimbus_posts_on_home,
'meta_key' => 'include_newsletter_feed',
'meta_value' => 'true',
);
$_topicts = get_posts($arg);
$_all_posts = array_merge ($_topicts, $_posts);
$ids = array();
foreach($_all_posts as $_post) {
$ids[] = $_post->ID;
}
/* Final query */
$wp_query = new WP_Query(array( "post_type" => array("product", "post", "page", "topic"), "post__in" => $ids ));
</code></pre>
|
[
{
"answer_id": 252957,
"author": "Ravi Shinde",
"author_id": 99294,
"author_profile": "https://wordpress.stackexchange.com/users/99294",
"pm_score": 2,
"selected": false,
"text": "<p>The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>I have tried this and it works well. </p>\n"
},
{
"answer_id": 253003,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 1,
"selected": false,
"text": "<p>looks like Ravi Shinde is right:</p>\n\n<blockquote>\n <p>The code you have shared can work in core PHP and not in Wordpress.\n Using AJAX in Wordpress plugin is explained in Wordpress\n documentation. Please refer -\n <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n</blockquote>\n\n<p>To give your plugin access to the ajax interface you need to wrap it around WordPress' AJAX action <code>wp_ajax_{action}</code></p>\n\n<p>First, you need to define the action:</p>\n\n<pre><code>add_action( 'wp_ajax_user_action', 'user_action' );\nadd_action( 'wp_ajax_nopriv_user_action', 'user_action' );\n</code></pre>\n\n<p>Which registers the <code>user_action</code> with wordpress for both logged in and not authenticated users.</p>\n\n<p>Then you build your handling function:</p>\n\n<pre><code>function user_action() {\n // since this gets loaded by wordpress\n // you get access to $wpdb and other\n // core functions\n global $wpdb; \n\n $state_name = $_POST['name']; \n\n $wpdb->insert( 'state',array( 'state_name' => $state_n),array('%s') );\n $status = $wpdb->insert_id;\n\n echo $status ? 'ok' : var_dump($wpdb);\n\n // Ajax calls in WP always need to be closed with wp_die:\n wp_die(); \n}\n</code></pre>\n\n<p>Finally, you need to get a reference the endpoint ( wordpress shares a single URL for all ajax calls ). In your JS:</p>\n\n<pre><code>var ajaxurl = <?php echo admin_url( 'admin-ajax.php' ); ?>;\n</code></pre>\n\n<p>Note: The \"correct\" way to register scripts is through <code>enqueue_scripts</code>, but thats beyond our scope right now.</p>\n\n<p>Then you can do a regular Ajax call to <code>ajaxurl</code> and passing <code>{ action: 'user_action' }</code> as data.</p>\n\n<p>Truth be told its not the best way, but you get used to it. If you need a primer, Smashinmag always has great articles: </p>\n\n<p><a href=\"https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/</a></p>\n\n<p>( Also: I haven't tested the code but is pretty standard and should work out of the box. Lemme know! )</p>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/252963",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111184/"
] |
How to make this query more simplest and in one query?
Problem - only topics has a meta\_key 'include\_newsletter\_feed'
So i need get all posts ("product", "post", "page") excluding categories (124, 52)
And join all topics with meta.
Example ugly code
```
$arg = array(
"post_type" => array("product", "post", "page"),
"posts_per_page" => 3,
'category__not_in' => array( 124 /*Gallery*/, 52 /* Discounts */ )
);
$_posts = get_posts($arg);
$arg = array(
"post_type" => "topic",
"posts_per_page" => $nimbus_posts_on_home,
'meta_key' => 'include_newsletter_feed',
'meta_value' => 'true',
);
$_topicts = get_posts($arg);
$_all_posts = array_merge ($_topicts, $_posts);
$ids = array();
foreach($_all_posts as $_post) {
$ids[] = $_post->ID;
}
/* Final query */
$wp_query = new WP_Query(array( "post_type" => array("product", "post", "page", "topic"), "post__in" => $ids ));
```
|
The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - <https://codex.wordpress.org/AJAX_in_Plugins>
I have tried this and it works well.
|
252,968 |
<p>Below is my code in which everything is working fine except when clicking read more button it's doing nothing</p>
<pre><code><?php get_header() ; ?>
<section class="container">
<div class="row">
<div class="col-sm-8">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<article class="blog">
<div class="blog-meta">
<h2 class="blog-meta-title"><a href="<?php the_permalink() ; ?>"><?php the_title() ; ?></a></h2>
<p class="blog-meta-detail">
Posted by <?php the_author_posts_link(); ?>
on <?php the_time('F j, Y'); ?>
Category <?php the_category(', ') ; ?>
Tag <?php if ( is_tag() ) {
the_tags('',', ','');
} else {
echo("No Tags Found");
} ?>
</p>
</div> <!-- .blog-meta -->
<?php if ( has_post_thumbnail() ) : ?>
<div class="blog-img">
<?php the_post_thumbnail('full',array(
'class' => 'img-responsive',
)); ?>
</div> <!-- .blog-img -->
<?php endif ; ?> <!-- if ends here of thumbnail -->
<div class="blog-excerpt">
<?php the_excerpt() ; ?>
</div> <!-- .blog-excerpt -->
<div class="blog-more">
<button class="btn btn-primary" href="<?php the_permalink() ; ?>">Read More</button>
</div> <!-- .blog-more -->
<div class="blog-hr">
<hr>
</div> <!-- .blog-hr -->
</article> <!-- .blog -->
<?php endwhile; else : ?> <!-- while ends here of post loop and else starts -->
<article class="blog">
<p><?php _e( 'Sorry, no posts found yo can always start writing' ); ?></p>
</article> <!-- .blog -->
<?php endif; ?> <!-- if ends here post loop -->
</div> <!-- .col-sm-8 -->
<div class="col-sm-4">
<?php get_sidebar() ; ?>
</div> <!-- .col-sm-4 -->
</div> <!-- .row -->
</section> <!-- .container -->
<?php get_footer() ; ?>
</code></pre>
<p>looks like dev in dev tool also link is showing correctly on read more button
<a href="https://i.stack.imgur.com/iRi1i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iRi1i.png" alt="enter image description here"></a>
thanks in advance for help.</p>
|
[
{
"answer_id": 252957,
"author": "Ravi Shinde",
"author_id": 99294,
"author_profile": "https://wordpress.stackexchange.com/users/99294",
"pm_score": 2,
"selected": false,
"text": "<p>The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>I have tried this and it works well. </p>\n"
},
{
"answer_id": 253003,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 1,
"selected": false,
"text": "<p>looks like Ravi Shinde is right:</p>\n\n<blockquote>\n <p>The code you have shared can work in core PHP and not in Wordpress.\n Using AJAX in Wordpress plugin is explained in Wordpress\n documentation. Please refer -\n <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n</blockquote>\n\n<p>To give your plugin access to the ajax interface you need to wrap it around WordPress' AJAX action <code>wp_ajax_{action}</code></p>\n\n<p>First, you need to define the action:</p>\n\n<pre><code>add_action( 'wp_ajax_user_action', 'user_action' );\nadd_action( 'wp_ajax_nopriv_user_action', 'user_action' );\n</code></pre>\n\n<p>Which registers the <code>user_action</code> with wordpress for both logged in and not authenticated users.</p>\n\n<p>Then you build your handling function:</p>\n\n<pre><code>function user_action() {\n // since this gets loaded by wordpress\n // you get access to $wpdb and other\n // core functions\n global $wpdb; \n\n $state_name = $_POST['name']; \n\n $wpdb->insert( 'state',array( 'state_name' => $state_n),array('%s') );\n $status = $wpdb->insert_id;\n\n echo $status ? 'ok' : var_dump($wpdb);\n\n // Ajax calls in WP always need to be closed with wp_die:\n wp_die(); \n}\n</code></pre>\n\n<p>Finally, you need to get a reference the endpoint ( wordpress shares a single URL for all ajax calls ). In your JS:</p>\n\n<pre><code>var ajaxurl = <?php echo admin_url( 'admin-ajax.php' ); ?>;\n</code></pre>\n\n<p>Note: The \"correct\" way to register scripts is through <code>enqueue_scripts</code>, but thats beyond our scope right now.</p>\n\n<p>Then you can do a regular Ajax call to <code>ajaxurl</code> and passing <code>{ action: 'user_action' }</code> as data.</p>\n\n<p>Truth be told its not the best way, but you get used to it. If you need a primer, Smashinmag always has great articles: </p>\n\n<p><a href=\"https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/</a></p>\n\n<p>( Also: I haven't tested the code but is pretty standard and should work out of the box. Lemme know! )</p>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/252968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100679/"
] |
Below is my code in which everything is working fine except when clicking read more button it's doing nothing
```
<?php get_header() ; ?>
<section class="container">
<div class="row">
<div class="col-sm-8">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<article class="blog">
<div class="blog-meta">
<h2 class="blog-meta-title"><a href="<?php the_permalink() ; ?>"><?php the_title() ; ?></a></h2>
<p class="blog-meta-detail">
Posted by <?php the_author_posts_link(); ?>
on <?php the_time('F j, Y'); ?>
Category <?php the_category(', ') ; ?>
Tag <?php if ( is_tag() ) {
the_tags('',', ','');
} else {
echo("No Tags Found");
} ?>
</p>
</div> <!-- .blog-meta -->
<?php if ( has_post_thumbnail() ) : ?>
<div class="blog-img">
<?php the_post_thumbnail('full',array(
'class' => 'img-responsive',
)); ?>
</div> <!-- .blog-img -->
<?php endif ; ?> <!-- if ends here of thumbnail -->
<div class="blog-excerpt">
<?php the_excerpt() ; ?>
</div> <!-- .blog-excerpt -->
<div class="blog-more">
<button class="btn btn-primary" href="<?php the_permalink() ; ?>">Read More</button>
</div> <!-- .blog-more -->
<div class="blog-hr">
<hr>
</div> <!-- .blog-hr -->
</article> <!-- .blog -->
<?php endwhile; else : ?> <!-- while ends here of post loop and else starts -->
<article class="blog">
<p><?php _e( 'Sorry, no posts found yo can always start writing' ); ?></p>
</article> <!-- .blog -->
<?php endif; ?> <!-- if ends here post loop -->
</div> <!-- .col-sm-8 -->
<div class="col-sm-4">
<?php get_sidebar() ; ?>
</div> <!-- .col-sm-4 -->
</div> <!-- .row -->
</section> <!-- .container -->
<?php get_footer() ; ?>
```
looks like dev in dev tool also link is showing correctly on read more button
[](https://i.stack.imgur.com/iRi1i.png)
thanks in advance for help.
|
The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - <https://codex.wordpress.org/AJAX_in_Plugins>
I have tried this and it works well.
|
252,976 |
<p>I am trying to fetch more posts on click via ajax. In my functions I have localised the script </p>
<pre><code>wp_enqueue_script( 'news', get_template_directory_uri().'/news/js/news.js', '', '', true );
//Localise script for ajax call
wp_localize_script( 'news', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => 'No Older Posts Found',
));
</code></pre>
<p>My Function for querying posts</p>
<pre><code>function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 2;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'paged' => $page
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .='<article class="post-container clearfix">
<div class="post-inner clearfix">
<div class="post-image">
'.get_the_post_thumbnail().'
</div>
<h1>'.the_title().'</h1>
<span class="date">Date: '.get_the_date().'</span>
<br>
<span class="author">Author: '.the_author().'</span>
<br>
'.get_custom_excerpt(get_the_content()).'
<a class="read-more" href="'.get_the_permalink().'" title="Read More"><img src="'.get_template_directory_uri().'/news/img/read-more.png" alt="Read More"></a>
</div>
</article>';
endwhile;
endif;
wp_reset_postdata();
echo $out;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
</code></pre>
<p>and then my jQuery</p>
<pre><code>jQuery(document).ready(function(){
var ppp = 2; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
jQuery.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
console.log(data);
var $data = jQuery(data);
if($data.length){
jQuery(".posts-wrapper").append($data);
jQuery(".load-more").attr("disabled",false);
} else{
jQuery(".load-more").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
jQuery(".load-more").on("click",function(e){ // When btn is pressed.
jQuery(".load-more").attr("disabled",true); // Disable the button, temp.
load_posts();
e.preventDefault();
});
});
</code></pre>
<p>The ajax response is always 0. Could anyone help please. </p>
|
[
{
"answer_id": 252988,
"author": "Anton Pedan",
"author_id": 105771,
"author_profile": "https://wordpress.stackexchange.com/users/105771",
"pm_score": 2,
"selected": false,
"text": "<p>Try die() function in the end of PHP function. It will helps.</p>\n\n<p>UPD: I<code>ve made some simple version of your problem code to check it and it works. I think it will helps you.\nYou are able to change inner PHP script to your logic and it won</code>t returns 0.</p>\n\n<p>PHP: </p>\n\n<pre><code>function more_post_ajax(){\n echo \"Hello\";\n die();\n}\nadd_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');\nadd_action('wp_ajax_more_post_ajax', 'more_post_ajax');\n\nfunction custom_scripts_init(){\n wp_enqueue_script( 'custom', get_template_directory_uri().'/assets/js/custom.js', array('jquery') );\n wp_localize_script( 'custom', 'ajaxPosts', array(\n 'customUrl' => admin_url( 'admin-ajax.php' ),\n 'noposts' => 'No Older Posts Found',\n));\n\n}\nadd_action('wp_footer', 'custom_scripts_init');\n</code></pre>\n\n<p>JQuery:</p>\n\n<pre><code>jQuery(document).ready(function(){\njQuery(\"#page\").append(\"<button type='button' class='load-more'/>\");\nvar ppp = 2; // Post per page\nvar pageNumber = 1;\n\n\nfunction load_posts(){\n pageNumber++;\n var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';\n jQuery.ajax({\n type: \"POST\",\n dataType: \"html\",\n url: ajaxPosts.customUrl,\n data: str,\n success: function(data){\n console.log(data);\n },\n error : function(jqXHR, textStatus, errorThrown) {\n //$loader.html(jqXHR + \" :: \" + textStatus + \" :: \" + errorThrown);\n }\n\n });\n return false;\n}\n\njQuery(\".load-more\").on(\"click\",function(e){ // When btn is pressed.\n\n // jQuery(\".load-more\").attr(\"disabled\",true); // Disable the button, temp.\n load_posts();\n\n e.preventDefault();\n\n});\n</code></pre>\n\n<p>});</p>\n"
},
{
"answer_id": 253005,
"author": "Liam O'Neill",
"author_id": 111192,
"author_profile": "https://wordpress.stackexchange.com/users/111192",
"pm_score": 0,
"selected": false,
"text": "<p>In case anyone comes to this, I just thought I would add what the issue was. </p>\n\n<p>I inherited the job from another developer and for reasons I will never understand there was ob_start at the top of the functions file. This was causing the ajax request to fail. </p>\n\n<p>Thanks</p>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/252976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111192/"
] |
I am trying to fetch more posts on click via ajax. In my functions I have localised the script
```
wp_enqueue_script( 'news', get_template_directory_uri().'/news/js/news.js', '', '', true );
//Localise script for ajax call
wp_localize_script( 'news', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => 'No Older Posts Found',
));
```
My Function for querying posts
```
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 2;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'paged' => $page
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .='<article class="post-container clearfix">
<div class="post-inner clearfix">
<div class="post-image">
'.get_the_post_thumbnail().'
</div>
<h1>'.the_title().'</h1>
<span class="date">Date: '.get_the_date().'</span>
<br>
<span class="author">Author: '.the_author().'</span>
<br>
'.get_custom_excerpt(get_the_content()).'
<a class="read-more" href="'.get_the_permalink().'" title="Read More"><img src="'.get_template_directory_uri().'/news/img/read-more.png" alt="Read More"></a>
</div>
</article>';
endwhile;
endif;
wp_reset_postdata();
echo $out;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
```
and then my jQuery
```
jQuery(document).ready(function(){
var ppp = 2; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
jQuery.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
console.log(data);
var $data = jQuery(data);
if($data.length){
jQuery(".posts-wrapper").append($data);
jQuery(".load-more").attr("disabled",false);
} else{
jQuery(".load-more").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
jQuery(".load-more").on("click",function(e){ // When btn is pressed.
jQuery(".load-more").attr("disabled",true); // Disable the button, temp.
load_posts();
e.preventDefault();
});
});
```
The ajax response is always 0. Could anyone help please.
|
Try die() function in the end of PHP function. It will helps.
UPD: I`ve made some simple version of your problem code to check it and it works. I think it will helps you.
You are able to change inner PHP script to your logic and it won`t returns 0.
PHP:
```
function more_post_ajax(){
echo "Hello";
die();
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
function custom_scripts_init(){
wp_enqueue_script( 'custom', get_template_directory_uri().'/assets/js/custom.js', array('jquery') );
wp_localize_script( 'custom', 'ajaxPosts', array(
'customUrl' => admin_url( 'admin-ajax.php' ),
'noposts' => 'No Older Posts Found',
));
}
add_action('wp_footer', 'custom_scripts_init');
```
JQuery:
```
jQuery(document).ready(function(){
jQuery("#page").append("<button type='button' class='load-more'/>");
var ppp = 2; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
jQuery.ajax({
type: "POST",
dataType: "html",
url: ajaxPosts.customUrl,
data: str,
success: function(data){
console.log(data);
},
error : function(jqXHR, textStatus, errorThrown) {
//$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
jQuery(".load-more").on("click",function(e){ // When btn is pressed.
// jQuery(".load-more").attr("disabled",true); // Disable the button, temp.
load_posts();
e.preventDefault();
});
```
});
|
253,032 |
<p>I have two wordpress installs each on their own sub domain.</p>
<p><strong>sub1.domain.com</strong> and <strong>sub2.domain.com</strong></p>
<p>I want to share the login information between sub1 and sub2. I already have configured them to use the same MySQL database, and they use the same database table.</p>
<p>I am able to log in on both websites with the same credentials.</p>
<p>Sub2's wp-config.php file has the following code:</p>
<pre><code>define('CUSTOM_USER_TABLE', 'wp_c_users');
define('CUSTOM_USERMETA_TABLE', 'wp_c_usermeta');
</code></pre>
<p>This all works great. My problem, is that the cookies are not being shared between the sites. Instead of sharing the cookies both sites just delete the others and create a new cookie.</p>
<p>I added the following code to both sub1 and sub2's wp-config.php:</p>
<pre><code>define('COOKIEPATH','domain.com/'); // Replace with your initial domain name
define('SITECOOKIEPATH','domain.com/'); // Replace with your initial domain name
define( 'COOKIEHASH', md5( 'Y@^ET#UF!RG7#KQXP04^WF' ) );
define('COOKIE_DOMAIN', 'domain.com');
</code></pre>
<p>When a user logs in to sub1, the cookie is created just fine, then when I go to sub2.domain.com, I am not also logged in on this site.</p>
<p>When I then try to log in to sub2.domain.com, it deletes sub1's cookies and overwrites them.</p>
<p>How can I get these two wordpress installations to use the same cookie instead of overwriting eachothers??</p>
<p>Any help much appreciated!</p>
|
[
{
"answer_id": 264504,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 1,
"selected": false,
"text": "<p>Today, I've posted a working solution for exactly the same problem. You can see it here: <a href=\"https://wordpress.stackexchange.com/questions/130753/how-to-share-wordpress-session-and-cookies-between-domain-and-subdomain/264490#264490\">How to share WordPress session and cookies between domain and subdomain?</a>. I use this method on several of my own websites.</p>\n"
},
{
"answer_id": 377351,
"author": "Lafif Astahdziq",
"author_id": 54707,
"author_profile": "https://wordpress.stackexchange.com/users/54707",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like you need to add a leading dot in the <code>COOKIE_DOMAIN</code> and just leave the <code>COOKIEPATH</code> and <code>SITECOOKIEPATH</code> undefined.</p>\n<p>So the constants would be</p>\n<pre><code>define( 'COOKIEHASH', md5( 'Y@^ET#UF!RG7#KQXP04^WF' ) );\ndefine( 'COOKIE_DOMAIN', '.domain.com' );\n</code></pre>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/253032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111226/"
] |
I have two wordpress installs each on their own sub domain.
**sub1.domain.com** and **sub2.domain.com**
I want to share the login information between sub1 and sub2. I already have configured them to use the same MySQL database, and they use the same database table.
I am able to log in on both websites with the same credentials.
Sub2's wp-config.php file has the following code:
```
define('CUSTOM_USER_TABLE', 'wp_c_users');
define('CUSTOM_USERMETA_TABLE', 'wp_c_usermeta');
```
This all works great. My problem, is that the cookies are not being shared between the sites. Instead of sharing the cookies both sites just delete the others and create a new cookie.
I added the following code to both sub1 and sub2's wp-config.php:
```
define('COOKIEPATH','domain.com/'); // Replace with your initial domain name
define('SITECOOKIEPATH','domain.com/'); // Replace with your initial domain name
define( 'COOKIEHASH', md5( 'Y@^ET#UF!RG7#KQXP04^WF' ) );
define('COOKIE_DOMAIN', 'domain.com');
```
When a user logs in to sub1, the cookie is created just fine, then when I go to sub2.domain.com, I am not also logged in on this site.
When I then try to log in to sub2.domain.com, it deletes sub1's cookies and overwrites them.
How can I get these two wordpress installations to use the same cookie instead of overwriting eachothers??
Any help much appreciated!
|
Today, I've posted a working solution for exactly the same problem. You can see it here: [How to share WordPress session and cookies between domain and subdomain?](https://wordpress.stackexchange.com/questions/130753/how-to-share-wordpress-session-and-cookies-between-domain-and-subdomain/264490#264490). I use this method on several of my own websites.
|
253,037 |
<p>I have used this function to change the number of posts per page on a category page, but I can't get it to work for a <strong>sub</strong>-category page. </p>
<p>I'm trying to show 6 posts on the sub-category page and 12 on the parent category page. </p>
<pre><code>function my_post_queries( $query ) {
if (!is_admin() && $query->is_main_query()){
if(cat_is_ancestor_of( 7, get_query_var( 'cat' ) ) ){
$query->set('posts_per_page', 6);
}
if(is_category( '7' )){
$query->set('posts_per_page', 12);
}
}
}
add_action( 'pre_get_posts', 'my_post_queries' );
</code></pre>
<p>When I use cat_is_ancestor_of on the archive page to change the layout of the sub-category page, it works, but when I use it in that function it doesn't. </p>
|
[
{
"answer_id": 264504,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 1,
"selected": false,
"text": "<p>Today, I've posted a working solution for exactly the same problem. You can see it here: <a href=\"https://wordpress.stackexchange.com/questions/130753/how-to-share-wordpress-session-and-cookies-between-domain-and-subdomain/264490#264490\">How to share WordPress session and cookies between domain and subdomain?</a>. I use this method on several of my own websites.</p>\n"
},
{
"answer_id": 377351,
"author": "Lafif Astahdziq",
"author_id": 54707,
"author_profile": "https://wordpress.stackexchange.com/users/54707",
"pm_score": 0,
"selected": false,
"text": "<p>Seems like you need to add a leading dot in the <code>COOKIE_DOMAIN</code> and just leave the <code>COOKIEPATH</code> and <code>SITECOOKIEPATH</code> undefined.</p>\n<p>So the constants would be</p>\n<pre><code>define( 'COOKIEHASH', md5( 'Y@^ET#UF!RG7#KQXP04^WF' ) );\ndefine( 'COOKIE_DOMAIN', '.domain.com' );\n</code></pre>\n"
}
] |
2017/01/18
|
[
"https://wordpress.stackexchange.com/questions/253037",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78026/"
] |
I have used this function to change the number of posts per page on a category page, but I can't get it to work for a **sub**-category page.
I'm trying to show 6 posts on the sub-category page and 12 on the parent category page.
```
function my_post_queries( $query ) {
if (!is_admin() && $query->is_main_query()){
if(cat_is_ancestor_of( 7, get_query_var( 'cat' ) ) ){
$query->set('posts_per_page', 6);
}
if(is_category( '7' )){
$query->set('posts_per_page', 12);
}
}
}
add_action( 'pre_get_posts', 'my_post_queries' );
```
When I use cat\_is\_ancestor\_of on the archive page to change the layout of the sub-category page, it works, but when I use it in that function it doesn't.
|
Today, I've posted a working solution for exactly the same problem. You can see it here: [How to share WordPress session and cookies between domain and subdomain?](https://wordpress.stackexchange.com/questions/130753/how-to-share-wordpress-session-and-cookies-between-domain-and-subdomain/264490#264490). I use this method on several of my own websites.
|
253,078 |
<p>I'm getting this in my json response</p>
<pre><code>"main_image":
[
"11125,11122,11123,11127,11128"
],
</code></pre>
<p>Those are the ID's of my post, I need to get the URL of each ID in the 'thumbnail' size. I did't find any solution, just this code but It's more for Custom Meta of a plugin.</p>
<pre><code>function xxx_past_poss_custom_metadata( $post_response, $post, $context ) {
$meta = get_post_custom( $post['ID'] );
$custom_fields = array();
$xxx_image_gallery = array();
foreach ( $meta['xxx_cmb_image_gallery'] as $key => $value ) {
$value = wp_get_attachment_url($value);
$xxx_image_gallery[ $key ] = $value;
};
foreach ( $meta as $key => $value ) {
// Replace 'xxx_' with any custom metakey prefix (ie. '_' for private metadata's)
if ( 'xxx_' !== substr( $key, 0, 1 ) ) {
$custom_fields[ $key ] = $value;
};
}
$post_response['xxx_image_gallery'] = $xxx_image_gallery;
$post_response['custom_fields'] = $custom_fields;
return $post_response;
}
add_filter( 'json_prepare_post', 'xxx_past_poss_custom_metadata', 10, 3 );
</code></pre>
<p>My meta it's called "media_gallery".</p>
<p>Any help will be very appreciated.</p>
<p>[UPDATE]</p>
<p>Seems like I wasn't even modifying my json response because of a plugin I had activated, turning it off made me declare my meta in my functions.php file and no I have this.</p>
<pre><code>add_action('rest_api_init', 'register_custom_fields', 1, 1);
function register_custom_fields(){
register_rest_field(
'job_listing',
'thumbnail',
array(
'get_callback' => 'show_image'
)
);
}
function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
return $main_image;
}
</code></pre>
<p>I can now modify the response but I still haven't been able to turn all this ID's: "11125,11122,11123,11127,11128" into URL sources.</p>
<p>My custom input saves the images id's like this: "11125,11122,11123,11127,11128", so was Pedro said is true it </p>
<blockquote>
<p>is an array with a single string inside</p>
</blockquote>
<p>What I tried next was this:</p>
<pre><code>function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
foreach ( $main_image as $key => $value ) {
$imagesID = explode(',',$value);
foreach ($imagesID as $id => $value) {
$result = wp_get_attachment_url($value);
$custom_fields[ $id ] = $result;
}
};
$image_urls = array();
return $result;
}
</code></pre>
<p>But still no luck, now the "main_image" endpoint appears to be empty.</p>
|
[
{
"answer_id": 253282,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 0,
"selected": false,
"text": "<p>based on your comment I think what you need is <code>wp_get_attachment_image_src</code>.</p>\n\n<p>Wordpress saves attachments ( like images ) as a type of post. Might seem silly, but this means it saves all sorts of meta information about it, such as diferent sizes, captions etc. As a result, each image gets a post ID.</p>\n\n<p>So assuming you have this array, which is parsed from your JSON:</p>\n\n<pre><code>$main_image = array( 11125, 11122, 11123, 11127, 11128 );\n</code></pre>\n\n<p>( Note that it seems your JSON is returning an array witha single string inside, instead of multiple integers )</p>\n\n<p>You simply go through requesting the image URL at thumbnail size:</p>\n\n<pre><code>$image_urls = array();\n\nforeach ( $main_image as $image_id ) {\n $image_urls[] = wp_get_attachent_image_src( $image_id, 'thumbnail' );\n}\n</code></pre>\n\n<p>Now <code>$image_urls</code> is populated with ... image urls :) </p>\n\n<p>Is that what you were looking for? </p>\n"
},
{
"answer_id": 254369,
"author": "Al Rosado",
"author_id": 84237,
"author_profile": "https://wordpress.stackexchange.com/users/84237",
"pm_score": 2,
"selected": false,
"text": "<p>This is the correct way to achieve it is this:</p>\n\n<pre><code>function show_main_image($object, $field_name, $request){\n $custom_fields = get_post_custom($object['id']);\n $main_image = $custom_fields['main_image'];\n $arregloimg = explode(',',$main_image[0]);\n\n $image_urls = array();\n foreach ( $arregloimg as $key => $value ) {\n $image_urls[] = wp_get_attachment_url($value,'thumbnail');\n };\n\n return $image_urls;\n}\n</code></pre>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84237/"
] |
I'm getting this in my json response
```
"main_image":
[
"11125,11122,11123,11127,11128"
],
```
Those are the ID's of my post, I need to get the URL of each ID in the 'thumbnail' size. I did't find any solution, just this code but It's more for Custom Meta of a plugin.
```
function xxx_past_poss_custom_metadata( $post_response, $post, $context ) {
$meta = get_post_custom( $post['ID'] );
$custom_fields = array();
$xxx_image_gallery = array();
foreach ( $meta['xxx_cmb_image_gallery'] as $key => $value ) {
$value = wp_get_attachment_url($value);
$xxx_image_gallery[ $key ] = $value;
};
foreach ( $meta as $key => $value ) {
// Replace 'xxx_' with any custom metakey prefix (ie. '_' for private metadata's)
if ( 'xxx_' !== substr( $key, 0, 1 ) ) {
$custom_fields[ $key ] = $value;
};
}
$post_response['xxx_image_gallery'] = $xxx_image_gallery;
$post_response['custom_fields'] = $custom_fields;
return $post_response;
}
add_filter( 'json_prepare_post', 'xxx_past_poss_custom_metadata', 10, 3 );
```
My meta it's called "media\_gallery".
Any help will be very appreciated.
[UPDATE]
Seems like I wasn't even modifying my json response because of a plugin I had activated, turning it off made me declare my meta in my functions.php file and no I have this.
```
add_action('rest_api_init', 'register_custom_fields', 1, 1);
function register_custom_fields(){
register_rest_field(
'job_listing',
'thumbnail',
array(
'get_callback' => 'show_image'
)
);
}
function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
return $main_image;
}
```
I can now modify the response but I still haven't been able to turn all this ID's: "11125,11122,11123,11127,11128" into URL sources.
My custom input saves the images id's like this: "11125,11122,11123,11127,11128", so was Pedro said is true it
>
> is an array with a single string inside
>
>
>
What I tried next was this:
```
function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
foreach ( $main_image as $key => $value ) {
$imagesID = explode(',',$value);
foreach ($imagesID as $id => $value) {
$result = wp_get_attachment_url($value);
$custom_fields[ $id ] = $result;
}
};
$image_urls = array();
return $result;
}
```
But still no luck, now the "main\_image" endpoint appears to be empty.
|
This is the correct way to achieve it is this:
```
function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
$arregloimg = explode(',',$main_image[0]);
$image_urls = array();
foreach ( $arregloimg as $key => $value ) {
$image_urls[] = wp_get_attachment_url($value,'thumbnail');
};
return $image_urls;
}
```
|
253,082 |
<p>My site URL in the database shows <code>sitea.com</code>. Is it possible to change this via <code>functions.php</code> into <code>siteb.com</code>, however still maintaining <code>sitea.com</code> in the database? </p>
<p>My current scenario is that I have three developers who work locally and we want to use one database. We all connect to a remote database, however, the URLs from our local development environment and from the remote database are different which causes broken links.</p>
<p>Is there some way to change the <code>siteurl</code> in <code>functions.php</code> while still having the same URL in the database? </p>
<p>Thanks in advance. </p>
|
[
{
"answer_id": 253100,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>theme_root_uri</code> filter will allow the URLs returned by <code>get_stylesheet_directory_uri()</code> and <code>get_template_directory_uri()</code> to be altered on the fly:</p>\n\n<pre><code>/**\n * Filters the URI for themes directory.\n *\n * @since 1.5.0\n *\n * @param string $theme_root_uri The URI for themes directory.\n * @param string $siteurl WordPress web address which is set in General Options.\n * @param string $stylesheet_or_template Stylesheet or template name of the theme.\n */\nfunction wpse_theme_root_uri( $theme_root_uri, $siteurl, $stylesheet_or_template ) {\n // $siteurl will be http://sitea.com via get_option( 'siteurl' )\n return str_replace( $siteurl, 'http://siteb.com', $theme_root_uri );\n}\nadd_filter( 'theme_root_uri', 'wpse_theme_root_uri', 10, 3 );\n</code></pre>\n\n<p>The <code>plugins_url</code> filter will allow the URL returned by <code>plugin_dir_url()</code> to be altered in a similar fashion:</p>\n\n<pre><code>/**\n * Filters the URL to the plugins directory.\n *\n * @since 2.8.0\n *\n * @param string $url The complete URL to the plugins directory including scheme and path.\n * @param string $path Path relative to the URL to the plugins directory. Blank string\n * if no path is specified.\n * @param string $plugin The plugin file path to be relative to. Blank string if no plugin\n * is specified.\n */\nfunction wpse_plugins_url( $url, $path, $plugin ) {\n return str_replace( get_option( 'siteurl' ), 'http://siteb.com', $url );\n}\nadd_filter( 'plugins_url', 'wpse_plugins_url', 10, 3 );\n</code></pre>\n\n<p>Looking through <code>/wp-includes/link-template.php</code>, there are quite a few other functions that return URLs, but they can be filtered using the same approach as demonstrated above.</p>\n\n<p>The values for the options <code>siteurl</code> and <code>home</code> can be modified on the fly as well:</p>\n\n<pre><code>function wpse_pre_option_siteurl_and_home( $pre_option, $option ) {\n return 'http://siteb.com';\n}\nadd_filter( 'pre_option_siteurl', 'wpse_pre_option_siteurl_and_home', 10, 2 );\nadd_filter( 'pre_option_home', 'wpse_pre_option_siteurl_and_home', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 253458,
"author": "fergbrain",
"author_id": 111481,
"author_profile": "https://wordpress.stackexchange.com/users/111481",
"pm_score": 2,
"selected": false,
"text": "<p>If instead of modifying functions.php you can modify wp-config.php, you can use the following:</p>\n\n<pre><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');\n</code></pre>\n\n<p><em>Source: <a href=\"https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php</a></em></p>\n"
},
{
"answer_id": 253459,
"author": "Matt Cromwell",
"author_id": 48338,
"author_profile": "https://wordpress.stackexchange.com/users/48338",
"pm_score": 2,
"selected": false,
"text": "<p>This shouldn't be handled by your theme at all, but your local wp-config.php file. You can conditionally load local and unique wp-config definitions by wrapping in a conditional <code>file_exists</code>. Here's an example from Mark Jaquith:</p>\n\n<pre><code>if ( file_exists( dirname( __FILE__ ) . '/local-config.php' ) ) {\n include( dirname( __FILE__ ) . '/local-config.php' );\n define( 'WP_LOCAL_DEV', true ); // We'll talk about this later\n} else {\n define( 'DB_NAME', 'production_db' );\n define( 'DB_USER', 'production_user' );\n define( 'DB_PASSWORD', 'production_password' );\n define( 'DB_HOST', 'production_db_host' );\n}\n</code></pre>\n\n<p>See here for more details:\n<a href=\"https://markjaquith.wordpress.com/2011/06/24/wordpress-local-dev-tips/\" rel=\"nofollow noreferrer\">https://markjaquith.wordpress.com/2011/06/24/wordpress-local-dev-tips/</a></p>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253082",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111250/"
] |
My site URL in the database shows `sitea.com`. Is it possible to change this via `functions.php` into `siteb.com`, however still maintaining `sitea.com` in the database?
My current scenario is that I have three developers who work locally and we want to use one database. We all connect to a remote database, however, the URLs from our local development environment and from the remote database are different which causes broken links.
Is there some way to change the `siteurl` in `functions.php` while still having the same URL in the database?
Thanks in advance.
|
If instead of modifying functions.php you can modify wp-config.php, you can use the following:
```
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
```
*Source: <https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php>*
|
253,092 |
<p>I noticed there are plugins to allow shortcode usage in widgets, and they obviously work on posts/pages, but they don't seem to work when added directly to the theme files.</p>
<p>Is there a way to allow shortcodes to work when added to a theme file?</p>
|
[
{
"answer_id": 253100,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>theme_root_uri</code> filter will allow the URLs returned by <code>get_stylesheet_directory_uri()</code> and <code>get_template_directory_uri()</code> to be altered on the fly:</p>\n\n<pre><code>/**\n * Filters the URI for themes directory.\n *\n * @since 1.5.0\n *\n * @param string $theme_root_uri The URI for themes directory.\n * @param string $siteurl WordPress web address which is set in General Options.\n * @param string $stylesheet_or_template Stylesheet or template name of the theme.\n */\nfunction wpse_theme_root_uri( $theme_root_uri, $siteurl, $stylesheet_or_template ) {\n // $siteurl will be http://sitea.com via get_option( 'siteurl' )\n return str_replace( $siteurl, 'http://siteb.com', $theme_root_uri );\n}\nadd_filter( 'theme_root_uri', 'wpse_theme_root_uri', 10, 3 );\n</code></pre>\n\n<p>The <code>plugins_url</code> filter will allow the URL returned by <code>plugin_dir_url()</code> to be altered in a similar fashion:</p>\n\n<pre><code>/**\n * Filters the URL to the plugins directory.\n *\n * @since 2.8.0\n *\n * @param string $url The complete URL to the plugins directory including scheme and path.\n * @param string $path Path relative to the URL to the plugins directory. Blank string\n * if no path is specified.\n * @param string $plugin The plugin file path to be relative to. Blank string if no plugin\n * is specified.\n */\nfunction wpse_plugins_url( $url, $path, $plugin ) {\n return str_replace( get_option( 'siteurl' ), 'http://siteb.com', $url );\n}\nadd_filter( 'plugins_url', 'wpse_plugins_url', 10, 3 );\n</code></pre>\n\n<p>Looking through <code>/wp-includes/link-template.php</code>, there are quite a few other functions that return URLs, but they can be filtered using the same approach as demonstrated above.</p>\n\n<p>The values for the options <code>siteurl</code> and <code>home</code> can be modified on the fly as well:</p>\n\n<pre><code>function wpse_pre_option_siteurl_and_home( $pre_option, $option ) {\n return 'http://siteb.com';\n}\nadd_filter( 'pre_option_siteurl', 'wpse_pre_option_siteurl_and_home', 10, 2 );\nadd_filter( 'pre_option_home', 'wpse_pre_option_siteurl_and_home', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 253458,
"author": "fergbrain",
"author_id": 111481,
"author_profile": "https://wordpress.stackexchange.com/users/111481",
"pm_score": 2,
"selected": false,
"text": "<p>If instead of modifying functions.php you can modify wp-config.php, you can use the following:</p>\n\n<pre><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');\n</code></pre>\n\n<p><em>Source: <a href=\"https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php</a></em></p>\n"
},
{
"answer_id": 253459,
"author": "Matt Cromwell",
"author_id": 48338,
"author_profile": "https://wordpress.stackexchange.com/users/48338",
"pm_score": 2,
"selected": false,
"text": "<p>This shouldn't be handled by your theme at all, but your local wp-config.php file. You can conditionally load local and unique wp-config definitions by wrapping in a conditional <code>file_exists</code>. Here's an example from Mark Jaquith:</p>\n\n<pre><code>if ( file_exists( dirname( __FILE__ ) . '/local-config.php' ) ) {\n include( dirname( __FILE__ ) . '/local-config.php' );\n define( 'WP_LOCAL_DEV', true ); // We'll talk about this later\n} else {\n define( 'DB_NAME', 'production_db' );\n define( 'DB_USER', 'production_user' );\n define( 'DB_PASSWORD', 'production_password' );\n define( 'DB_HOST', 'production_db_host' );\n}\n</code></pre>\n\n<p>See here for more details:\n<a href=\"https://markjaquith.wordpress.com/2011/06/24/wordpress-local-dev-tips/\" rel=\"nofollow noreferrer\">https://markjaquith.wordpress.com/2011/06/24/wordpress-local-dev-tips/</a></p>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253092",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94819/"
] |
I noticed there are plugins to allow shortcode usage in widgets, and they obviously work on posts/pages, but they don't seem to work when added directly to the theme files.
Is there a way to allow shortcodes to work when added to a theme file?
|
If instead of modifying functions.php you can modify wp-config.php, you can use the following:
```
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
```
*Source: <https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php>*
|
253,098 |
<p>I'm loading posts via Ajax into a div that I have set up on index page.</p>
<p><strong>index page loop:</strong></p>
<pre><code> <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div>
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<?php the_post_thumbnail(); ?>
<a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title(); ?></a>
</div>
<?php endwhile; endif; ?>
</code></pre>
<p><strong>Div:</strong></p>
<pre><code><div id="post-container"></div>
</code></pre>
<p><strong>script:</strong></p>
<pre><code><Script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_link = $(this);
$("#post-container").html("loading...");
$("#post-container").load(post_link);
return false;
});
});
</script>
</code></pre>
<p><strong>How to add posts into div with ajax and assign them specific post format?</strong> </p>
|
[
{
"answer_id": 253102,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 3,
"selected": true,
"text": "<p>First of all you need to <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">register a action callback</a> for you ajax request.<br>\nSecondly you need to send all ajax request to <code>wp-admin/admin-ajax.php</code> (both <code>GET</code> and <code>POST</code>).<br>\nAnd lastly you need to modify your javascript a little to pass the <code>action</code> parameter which will trigger the callback. and <code>var post_link = $(this);</code> doesn't gives the post id from rel attribute you should use <code>var post_link = $(this).attr(\"rel\");</code></p>\n\n<p>You can get the ajax url by <code>admin_url( 'admin-ajax.php' );</code> in your theme. and use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">javascript localization</a> to get inside your js.</p>\n\n<p>Everything else looks good on your index.php</p>\n\n<p><strong>Example</strong></p>\n\n<p><em>JavaScript</em><br></p>\n\n<pre><code>$(document).ready(function(){\n $.ajaxSetup({cache:false});\n $(\".post-link\").click(function(){\n var post_id = $(this).attr(\"rel\");\n $(\"#post-container\").html(\"loading...\");\n //$(\"#post-container\").load(post_link+\"?action=load_more_post&pid=\"+post_id);\n // update: .load() should send request to ajax url not the post url\n $(\"#post-container\").load(ajax_url+\"?action=load_more_post&pid=\"+post_id);\n return false;\n });\n});\n</code></pre>\n\n<p><em>PHP (in your theme's function.php)</em><br></p>\n\n<pre><code>add_action( 'wp_ajax_load_more_post', 'load_more_post_callback' );\nadd_action( 'wp_ajax_nopriv_load_more_post', 'load_more_post_callback' );\n\nfunction load_more_post_callback() {\n if( isset($_GET[\"pid\"]) ){\n $post = get_post( $_GET[\"pid\"] );\n if( $post instanceof WP_Post ) {\n echo '<h1 class=\"post_title\">'.$post->post_title.'</h1>';\n } else {\n // nothing found with the post id\n }\n } else {\n // no post id\n }\n wp_die();\n}\n</code></pre>\n"
},
{
"answer_id": 412063,
"author": "Abu Nabil",
"author_id": 228270,
"author_profile": "https://wordpress.stackexchange.com/users/228270",
"pm_score": 0,
"selected": false,
"text": "<p>To load a post into a div using Ajax, you can use the <code>.load()</code> method in jQuery. This method fetches the HTML content of the specified post and inserts it into the div with the specified id.</p>\n<p>Here's an example of how you might modify your code to do this:</p>\n<pre><code><script>\n $(document).ready(function(){\n\n // Set the ajax cache to false\n $.ajaxSetup({cache:false});\n\n // Handle the click event for the post link buttons\n $(".post-link").click(function(){\n var post_link = $(this);\n\n // Set the text of the post container to "loading..." while the post is being fetched\n $("#post-container").html("loading...");\n\n // Load the post using the post_link button's rel attribute, which contains the post's ID\n $("#post-container").load(post_link.attr('rel'));\n\n // Prevent the default link behavior\n return false;\n });\n\n });\n</script>\n</code></pre>\n<p>To specify a particular post format for the loaded post, you can pass the post format as a query string parameter to the <code>.load()</code> method. For example, to load the post in the "aside" format, you could use the following code:</p>\n<pre><code>$("#post-container").load(post_link.attr('rel') + "?format=aside");\n</code></pre>\n<p>You can change the "aside" parameter to any other post format that you want to use for the loaded post.</p>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253098",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97572/"
] |
I'm loading posts via Ajax into a div that I have set up on index page.
**index page loop:**
```
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div>
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<?php the_post_thumbnail(); ?>
<a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title(); ?></a>
</div>
<?php endwhile; endif; ?>
```
**Div:**
```
<div id="post-container"></div>
```
**script:**
```
<Script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_link = $(this);
$("#post-container").html("loading...");
$("#post-container").load(post_link);
return false;
});
});
</script>
```
**How to add posts into div with ajax and assign them specific post format?**
|
First of all you need to [register a action callback](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)) for you ajax request.
Secondly you need to send all ajax request to `wp-admin/admin-ajax.php` (both `GET` and `POST`).
And lastly you need to modify your javascript a little to pass the `action` parameter which will trigger the callback. and `var post_link = $(this);` doesn't gives the post id from rel attribute you should use `var post_link = $(this).attr("rel");`
You can get the ajax url by `admin_url( 'admin-ajax.php' );` in your theme. and use [javascript localization](https://codex.wordpress.org/Function_Reference/wp_localize_script) to get inside your js.
Everything else looks good on your index.php
**Example**
*JavaScript*
```
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_id = $(this).attr("rel");
$("#post-container").html("loading...");
//$("#post-container").load(post_link+"?action=load_more_post&pid="+post_id);
// update: .load() should send request to ajax url not the post url
$("#post-container").load(ajax_url+"?action=load_more_post&pid="+post_id);
return false;
});
});
```
*PHP (in your theme's function.php)*
```
add_action( 'wp_ajax_load_more_post', 'load_more_post_callback' );
add_action( 'wp_ajax_nopriv_load_more_post', 'load_more_post_callback' );
function load_more_post_callback() {
if( isset($_GET["pid"]) ){
$post = get_post( $_GET["pid"] );
if( $post instanceof WP_Post ) {
echo '<h1 class="post_title">'.$post->post_title.'</h1>';
} else {
// nothing found with the post id
}
} else {
// no post id
}
wp_die();
}
```
|
253,114 |
<p>I was wondering how to achieve this navigation style in WordPress. The menu structure is like this --</p>
<pre><code><ul>
<li>
<a href="index.php">
Home
<span>
MAIN PAGE
</span>
</a>
</li>
</ul>
</code></pre>
<p><a href="https://i.stack.imgur.com/4gSMZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4gSMZ.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 253102,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 3,
"selected": true,
"text": "<p>First of all you need to <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">register a action callback</a> for you ajax request.<br>\nSecondly you need to send all ajax request to <code>wp-admin/admin-ajax.php</code> (both <code>GET</code> and <code>POST</code>).<br>\nAnd lastly you need to modify your javascript a little to pass the <code>action</code> parameter which will trigger the callback. and <code>var post_link = $(this);</code> doesn't gives the post id from rel attribute you should use <code>var post_link = $(this).attr(\"rel\");</code></p>\n\n<p>You can get the ajax url by <code>admin_url( 'admin-ajax.php' );</code> in your theme. and use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">javascript localization</a> to get inside your js.</p>\n\n<p>Everything else looks good on your index.php</p>\n\n<p><strong>Example</strong></p>\n\n<p><em>JavaScript</em><br></p>\n\n<pre><code>$(document).ready(function(){\n $.ajaxSetup({cache:false});\n $(\".post-link\").click(function(){\n var post_id = $(this).attr(\"rel\");\n $(\"#post-container\").html(\"loading...\");\n //$(\"#post-container\").load(post_link+\"?action=load_more_post&pid=\"+post_id);\n // update: .load() should send request to ajax url not the post url\n $(\"#post-container\").load(ajax_url+\"?action=load_more_post&pid=\"+post_id);\n return false;\n });\n});\n</code></pre>\n\n<p><em>PHP (in your theme's function.php)</em><br></p>\n\n<pre><code>add_action( 'wp_ajax_load_more_post', 'load_more_post_callback' );\nadd_action( 'wp_ajax_nopriv_load_more_post', 'load_more_post_callback' );\n\nfunction load_more_post_callback() {\n if( isset($_GET[\"pid\"]) ){\n $post = get_post( $_GET[\"pid\"] );\n if( $post instanceof WP_Post ) {\n echo '<h1 class=\"post_title\">'.$post->post_title.'</h1>';\n } else {\n // nothing found with the post id\n }\n } else {\n // no post id\n }\n wp_die();\n}\n</code></pre>\n"
},
{
"answer_id": 412063,
"author": "Abu Nabil",
"author_id": 228270,
"author_profile": "https://wordpress.stackexchange.com/users/228270",
"pm_score": 0,
"selected": false,
"text": "<p>To load a post into a div using Ajax, you can use the <code>.load()</code> method in jQuery. This method fetches the HTML content of the specified post and inserts it into the div with the specified id.</p>\n<p>Here's an example of how you might modify your code to do this:</p>\n<pre><code><script>\n $(document).ready(function(){\n\n // Set the ajax cache to false\n $.ajaxSetup({cache:false});\n\n // Handle the click event for the post link buttons\n $(".post-link").click(function(){\n var post_link = $(this);\n\n // Set the text of the post container to "loading..." while the post is being fetched\n $("#post-container").html("loading...");\n\n // Load the post using the post_link button's rel attribute, which contains the post's ID\n $("#post-container").load(post_link.attr('rel'));\n\n // Prevent the default link behavior\n return false;\n });\n\n });\n</script>\n</code></pre>\n<p>To specify a particular post format for the loaded post, you can pass the post format as a query string parameter to the <code>.load()</code> method. For example, to load the post in the "aside" format, you could use the following code:</p>\n<pre><code>$("#post-container").load(post_link.attr('rel') + "?format=aside");\n</code></pre>\n<p>You can change the "aside" parameter to any other post format that you want to use for the loaded post.</p>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111268/"
] |
I was wondering how to achieve this navigation style in WordPress. The menu structure is like this --
```
<ul>
<li>
<a href="index.php">
Home
<span>
MAIN PAGE
</span>
</a>
</li>
</ul>
```
[](https://i.stack.imgur.com/4gSMZ.png)
|
First of all you need to [register a action callback](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)) for you ajax request.
Secondly you need to send all ajax request to `wp-admin/admin-ajax.php` (both `GET` and `POST`).
And lastly you need to modify your javascript a little to pass the `action` parameter which will trigger the callback. and `var post_link = $(this);` doesn't gives the post id from rel attribute you should use `var post_link = $(this).attr("rel");`
You can get the ajax url by `admin_url( 'admin-ajax.php' );` in your theme. and use [javascript localization](https://codex.wordpress.org/Function_Reference/wp_localize_script) to get inside your js.
Everything else looks good on your index.php
**Example**
*JavaScript*
```
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_id = $(this).attr("rel");
$("#post-container").html("loading...");
//$("#post-container").load(post_link+"?action=load_more_post&pid="+post_id);
// update: .load() should send request to ajax url not the post url
$("#post-container").load(ajax_url+"?action=load_more_post&pid="+post_id);
return false;
});
});
```
*PHP (in your theme's function.php)*
```
add_action( 'wp_ajax_load_more_post', 'load_more_post_callback' );
add_action( 'wp_ajax_nopriv_load_more_post', 'load_more_post_callback' );
function load_more_post_callback() {
if( isset($_GET["pid"]) ){
$post = get_post( $_GET["pid"] );
if( $post instanceof WP_Post ) {
echo '<h1 class="post_title">'.$post->post_title.'</h1>';
} else {
// nothing found with the post id
}
} else {
// no post id
}
wp_die();
}
```
|
253,133 |
<p>My current site has custom post types, that run of off the root domain, so anything created inside the CPT will be something like: domain.com/page-name/ rather than domain.com/custom-post-type-name/post-name/. With this, I want to update to WP 4.7 but I cannot because it breaks my website and the CPT's mess up.</p>
<p>Here's why I'm using custom post types, so I have this page template that pulls in everything related to that custom post type and displays those pages a list (similar to the blog page). </p>
<p>However, seeing as everything is of off the root. I was wondering if there was a way to customise Wordpress to give me the option to add a category to a PAGE, therefore, after I can create a code that will display all PAGES within that CATEGORY as a page template.</p>
<p>Reason for this, is will allow me to update to Wordpress 4.7 and not have 5-10 different CPT's as it just gets annoying clicking between the different custom post type labels in the backend.</p>
<p>If anyone has any ideas or know's off a plugin that will do this.</p>
<p>And maybe if some has the code to show all pages as a list, that sit under that category, that would be great - please share.</p>
<p>Thanks.</p>
<p><strong>Update</strong></p>
<p>Here's my code for loop:</p>
<pre><code><?php wp_reset_query(); ?>
<?php $query = new WP_Query( array( post_type=page, 'cat' => 541 ) ); ?>
</code></pre>
have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<p></p>
<pre><code> <?php if(has_post_thumbnail()) {
the_post_thumbnail(array(150,150));
} else {
echo '<img class="alignleft" src="'.get_bloginfo("template_url").'/images/empty_150_150_thumb.gif" width="150" height="150" />';
}
?>
<div class="entry">
<h3 class="blog_header"><a href="<?php echo get_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
<a class="button_link" href="<?php the_permalink(); ?>"><span>Read More</span></a>
</div>
</div>
</code></pre>
<p></p>
<p>I'm attempting to display the pages that have been added to that category within a loop. Is there something wrong with my loop?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 253135,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 2,
"selected": false,
"text": "<p>checkout this <a href=\"https://stackoverflow.com/questions/14323582/wordpress-how-to-add-categories-and-tags-on-pages\">solution by @Matoeil</a> </p>\n\n<pre><code>function myplugin_settings() { \n// Add tag metabox to page\nregister_taxonomy_for_object_type('post_tag', 'page'); \n// Add category metabox to page\nregister_taxonomy_for_object_type('category', 'page'); \n}\n // Add to the admin_init hook of your theme functions.php file \nadd_action( 'init', 'myplugin_settings' );\n</code></pre>\n"
},
{
"answer_id": 253156,
"author": "Jared Counts",
"author_id": 111301,
"author_profile": "https://wordpress.stackexchange.com/users/111301",
"pm_score": 1,
"selected": true,
"text": "<p>If you don't want to attach the default post category taxonomy, you can always create a new one specifically for pages. Insert this into your <code>functions.php</code> file:</p>\n\n<pre><code>add_action( 'init', 'create_page_taxonomies' );\nfunction create_page_taxonomies() {\n register_taxonomy('page_category', 'page', array(\n 'hierarchical' => true,\n 'labels' => array(\n 'name' => _x( 'Page Category', 'taxonomy general name' ),\n 'singular_name' => _x( 'page-category', 'taxonomy singular name' ),\n 'search_items' => __( 'Search Page Categories' ),\n 'all_items' => __( 'All Page Categories' ),\n 'parent_item' => __( 'Parent Page Category' ),\n 'parent_item_colon' => __( 'Parent Page Category:' ),\n 'edit_item' => __( 'Edit Page Category' ),\n 'update_item' => __( 'Update Page Category' ),\n 'add_new_item' => __( 'Add New Page Category' ),\n 'new_item_name' => __( 'New Page Category Name' ),\n 'menu_name' => __( 'Page Categories' )\n ),\n 'public' => true,\n 'rewrite' => array(\n 'slug' => 'page-category',\n 'with_front' => false,\n 'hierarchical' => true\n )\n ));\n}\n</code></pre>\n\n<p>This is a fairly bare-bones new taxonomy, and there are plenty of other options available, of which there is a complete listing <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow noreferrer\">in the WP Codex</a>.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>I believe that this is what the whole loop would look like:</p>\n\n<pre><code><?php\n wp_reset_query();\n $query = new WP_Query(\n array(\n 'post_type' => 'page',\n 'tax_query' => array(\n array( \n 'taxonomy' => 'page_category',\n 'field' => 'term_id',\n 'terms' => 541\n )\n )\n )\n );\n if ( $query->have_posts() ) :\n while ( $query->have_posts() ) : $query->the_post(); ?>\n <div>\n<?php\n if ( has_post_thumbnail() ) :\n the_post_thumbnail( array(150,150) );\n else : ?>\n <img class=\"alignleft\" src=\"<?php echo get_bloginfo(\"template_url\"); ?>/images/empty_150_150_thumb.gif\" width=\"150\" height=\"150\" />\n<?php\n endif; ?>\n <div class=\"entry\">\n <h3 class=\"blog_header\"><a href=\"<?php echo get_permalink(); ?>\" rel=\"bookmark\" title=\"Permanent Link: <?php the_title(); ?>\"><?php the_title(); ?></a></h3>\n <?php the_excerpt(); ?>\n <a class=\"button_link\" href=\"<?php the_permalink(); ?>\"><span>Read More</span></a>\n </div>\n </div>\n<?php\n endwhile;\n endif; ?>\n</code></pre>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253133",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98494/"
] |
My current site has custom post types, that run of off the root domain, so anything created inside the CPT will be something like: domain.com/page-name/ rather than domain.com/custom-post-type-name/post-name/. With this, I want to update to WP 4.7 but I cannot because it breaks my website and the CPT's mess up.
Here's why I'm using custom post types, so I have this page template that pulls in everything related to that custom post type and displays those pages a list (similar to the blog page).
However, seeing as everything is of off the root. I was wondering if there was a way to customise Wordpress to give me the option to add a category to a PAGE, therefore, after I can create a code that will display all PAGES within that CATEGORY as a page template.
Reason for this, is will allow me to update to Wordpress 4.7 and not have 5-10 different CPT's as it just gets annoying clicking between the different custom post type labels in the backend.
If anyone has any ideas or know's off a plugin that will do this.
And maybe if some has the code to show all pages as a list, that sit under that category, that would be great - please share.
Thanks.
**Update**
Here's my code for loop:
```
<?php wp_reset_query(); ?>
<?php $query = new WP_Query( array( post_type=page, 'cat' => 541 ) ); ?>
```
have\_posts() ) : while ( $query->have\_posts() ) : $query->the\_post(); ?>
```
<?php if(has_post_thumbnail()) {
the_post_thumbnail(array(150,150));
} else {
echo '<img class="alignleft" src="'.get_bloginfo("template_url").'/images/empty_150_150_thumb.gif" width="150" height="150" />';
}
?>
<div class="entry">
<h3 class="blog_header"><a href="<?php echo get_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
<a class="button_link" href="<?php the_permalink(); ?>"><span>Read More</span></a>
</div>
</div>
```
I'm attempting to display the pages that have been added to that category within a loop. Is there something wrong with my loop?
Thanks.
|
If you don't want to attach the default post category taxonomy, you can always create a new one specifically for pages. Insert this into your `functions.php` file:
```
add_action( 'init', 'create_page_taxonomies' );
function create_page_taxonomies() {
register_taxonomy('page_category', 'page', array(
'hierarchical' => true,
'labels' => array(
'name' => _x( 'Page Category', 'taxonomy general name' ),
'singular_name' => _x( 'page-category', 'taxonomy singular name' ),
'search_items' => __( 'Search Page Categories' ),
'all_items' => __( 'All Page Categories' ),
'parent_item' => __( 'Parent Page Category' ),
'parent_item_colon' => __( 'Parent Page Category:' ),
'edit_item' => __( 'Edit Page Category' ),
'update_item' => __( 'Update Page Category' ),
'add_new_item' => __( 'Add New Page Category' ),
'new_item_name' => __( 'New Page Category Name' ),
'menu_name' => __( 'Page Categories' )
),
'public' => true,
'rewrite' => array(
'slug' => 'page-category',
'with_front' => false,
'hierarchical' => true
)
));
}
```
This is a fairly bare-bones new taxonomy, and there are plenty of other options available, of which there is a complete listing [in the WP Codex](https://codex.wordpress.org/Function_Reference/register_taxonomy).
**UPDATE:**
I believe that this is what the whole loop would look like:
```
<?php
wp_reset_query();
$query = new WP_Query(
array(
'post_type' => 'page',
'tax_query' => array(
array(
'taxonomy' => 'page_category',
'field' => 'term_id',
'terms' => 541
)
)
)
);
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post(); ?>
<div>
<?php
if ( has_post_thumbnail() ) :
the_post_thumbnail( array(150,150) );
else : ?>
<img class="alignleft" src="<?php echo get_bloginfo("template_url"); ?>/images/empty_150_150_thumb.gif" width="150" height="150" />
<?php
endif; ?>
<div class="entry">
<h3 class="blog_header"><a href="<?php echo get_permalink(); ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
<a class="button_link" href="<?php the_permalink(); ?>"><span>Read More</span></a>
</div>
</div>
<?php
endwhile;
endif; ?>
```
|
253,134 |
<p>Is there a way to remove "Save draft" button without the use of CSS?</p>
|
[
{
"answer_id": 253136,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": -1,
"selected": false,
"text": "<p>Please put the below lines in your wp-config.php </p>\n\n<pre><code>define('WP_POST_REVISIONS', 'false');\n</code></pre>\n"
},
{
"answer_id": 316211,
"author": "Felix Eve",
"author_id": 31597,
"author_profile": "https://wordpress.stackexchange.com/users/31597",
"pm_score": 1,
"selected": false,
"text": "<p>You cannot just remove the \"Save draft\" as the button is tied up in the <code>submitdiv</code> metabox HTML defined in the function <code>post_submit_meta_box()</code>.</p>\n\n<p>However we can alter the callback for this metabox and replace it with our own function.</p>\n\n<p>We can bind to the <code>submitpost_box</code> event and give the binding a height weight so it fires last...</p>\n\n<pre><code>add_action('submitpost_box', 'my_module_edit_form_after_editor', 100);\n</code></pre>\n\n<p>Then when our action is called we can swap out the metabox callback:</p>\n\n<pre><code>function my_module_edit_form_after_editor() {\n global $wp_meta_boxes;\n\n $post_type = 'feed';\n $context = 'side';\n $priority = 'core';\n\n $wp_meta_boxes[$post_type][$context][$priority]['submitdiv']['callback'] = 'my_custom_post_submit_meta_box';\n\n}\n</code></pre>\n\n<p>And then we just need to define what our custom metabox will look like. You could just take the core function <code>post_submit_meta_box()</code> and put it into your own plugin removing the unneeded sections, however I would recommend using an actual template and not just closing php tags half way though a function as that just leads to difficult to follow horrible spaghetti code.</p>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109705/"
] |
Is there a way to remove "Save draft" button without the use of CSS?
|
You cannot just remove the "Save draft" as the button is tied up in the `submitdiv` metabox HTML defined in the function `post_submit_meta_box()`.
However we can alter the callback for this metabox and replace it with our own function.
We can bind to the `submitpost_box` event and give the binding a height weight so it fires last...
```
add_action('submitpost_box', 'my_module_edit_form_after_editor', 100);
```
Then when our action is called we can swap out the metabox callback:
```
function my_module_edit_form_after_editor() {
global $wp_meta_boxes;
$post_type = 'feed';
$context = 'side';
$priority = 'core';
$wp_meta_boxes[$post_type][$context][$priority]['submitdiv']['callback'] = 'my_custom_post_submit_meta_box';
}
```
And then we just need to define what our custom metabox will look like. You could just take the core function `post_submit_meta_box()` and put it into your own plugin removing the unneeded sections, however I would recommend using an actual template and not just closing php tags half way though a function as that just leads to difficult to follow horrible spaghetti code.
|
253,144 |
<p>I'm fairly new to Wordpress and I'm a little confuse on how to take the database from my local server and replace it with the one on the server on a Wordpress multisite.</p>
<p>I've replace database before from local to server, but it was a multisite.</p>
<p>The step I usually take is:</p>
<ol>
<li>backup the database on the server </li>
<li>export local database </li>
<li>drop all table on the server database </li>
<li>import the local database </li>
<li>go to wp_option </li>
<li>change value for siteurl and home to the site url</li>
</ol>
<p>When I try that, the table on the server is very different from the one on my local.</p>
<p>My local database structure looks like this:</p>
<p><a href="https://i.stack.imgur.com/EDSJo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EDSJo.png" alt="enter image description here"></a></p>
<p>Usually the server database is the same, but not in this case though. </p>
<p>Server database structure:</p>
<p><a href="https://i.stack.imgur.com/5itEC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5itEC.png" alt="enter image description here"></a></p>
<p>So i'm a little confuse on how to tackle this. Can I still do what I usually do, or is there additional steps I need to take?</p>
<p>Thanks in advance.</p>
<p>Edit: Think I overcomplicated this a bit, I could just create a new database on the server and point the wp_config.php file to that instead and everything should be good</p>
<p>Edit 2: nope doesn't work like I thought it would. keep getting redirect loop error</p>
<p>Edit 3: I finally got everything to migrate properly all thanks to <a href="https://wordpress.stackexchange.com/users/9579/michael-ecklund">@Michael Ecklund</a>! Since I was updating the database of the primary page I didn't need to create a new site, but still follow the rest of the <a href="https://wordpress.stackexchange.com/a/253175/101431">instruction</a> he wrote and it went fairly smooth. A bit of confusion at first, but that was my own lack of knowledge.</p>
<p>Edit 4: Just a FYI, if after doing the database migration and you somehow lost access to the dashboard. Go into your main database and in the *_options (in my case the tenp_options) table and look for an <code>wp_user_roles</code> under the option_name column and change that column name to your site prefix (which in my case is <code>tenp_</code>) and you should now be able to access your dashboard again.</p>
|
[
{
"answer_id": 253147,
"author": "DGRFDSGN",
"author_id": 108736,
"author_profile": "https://wordpress.stackexchange.com/users/108736",
"pm_score": 1,
"selected": false,
"text": "<p>The database is indeed configured different for a multiwp, those tenp_12 are prefixes for each site in the multisite. It seems the site you run locally isnt a multisite. My suggestion if you're trying to add another site (not primary) is to first add it from the multisite dashboard, drop tables on that one (i.e. tenp_x where x resembles your site id) and import into those tables. This would require you to preamptive rename the table name aswell as collumns, after which you may configure value for siteurl and home to the site url as you describe in point 6.</p>\n"
},
{
"answer_id": 253175,
"author": "Michael Ecklund",
"author_id": 9579,
"author_profile": "https://wordpress.stackexchange.com/users/9579",
"pm_score": 2,
"selected": true,
"text": "<h2>Merging WordPress Standalone Installation with WordPress Multisite Installation</h2>\n\n<p><strong>Before You Begin:</strong></p>\n\n<ol>\n<li>Create a new site in your Multisite Network, which will be the site\nyou're migrating from the Standalone installation. (Take note of the site ID #, you'll need it later.)</li>\n<li>You need to make sure that all of the users from the Standalone\ninstallation, are created and exist in the Multisite installation.</li>\n</ol>\n\n<h2>Step 1 - Backup Databases.</h2>\n\n<p>Find the directory on your Web Server which the the Standalone copy of WordPress is installed and the directory on your Web Server which the Multisite copy of WordPress is installed and open the <code>wp-config.php</code> file of both installations. Locate the PHP constant <code>DB_NAME</code>. It contains the name of the database that particular installation of WordPress is using.</p>\n\n<ol>\n<li>Backup the Standalone instillation's database.</li>\n<li>Backup the Multisite installation's database.</li>\n</ol>\n\n<h2>Step 2 - Identify the Database Table Prefixes.</h2>\n\n<p><em>By default the database table prefix is <code>wp_</code>.</em></p>\n\n<p>If you can't identify the database table prefix just by examining the database. You can look in the base directory of your WordPress installation and open the <code>wp-config.php</code> file of the site in question and look for a line like <code>$table_prefix = 'wp_';</code>.</p>\n\n<p><strong>In your situation, it looks like:</strong></p>\n\n<ul>\n<li>The Standalone installation's database table prefix is the default of\n<code>wp_</code>.</li>\n<li>The Multisite installation's database table prefix is custom of\n<code>tenp_</code>.</li>\n</ul>\n\n<h2>Step 3 - Export Databases. Import Into Local Environment.</h2>\n\n<p>On a local Database Server, create a temporary database for each of these databases. Perhaps to keep things simple, label one database \"<code>standalone</code>\", and the second one \"<code>multisite</code>\".</p>\n\n<ul>\n<li>Import the Standalone installation's database (which you just\nexported) into the \"<code>standalone</code>\" database (which you just created) on\nyour local Database Server.</li>\n<li>Import the Multisite installation's database (which you just\nexported) into the \"<code>multisite</code>\" database (which you just created) on\nyour local Database Server.</li>\n</ul>\n\n<h2>Step 4 - Search and Replace.</h2>\n\n<p>This is the step where you would likely replace any necessary URL changes. (http to https), (non-www to www), (add or remove directories from URL), etc.</p>\n\n<p>Perform this task on the \"<code>standalone</code>\" database you created on your local Database Server.</p>\n\n<p>Remember to change things to how you would like them to be in the Multisite installation (the end result).</p>\n\n<p><strong>For this procedure, you're going to need a Database Tool:</strong></p>\n\n<ol>\n<li><a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow noreferrer\">WP-CLI :: wp search-replace</a> which is\nall command line.</li>\n<li>Alternatively, if you prefer a GUI, there's the <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">Database Search and\nReplace Script in PHP by\ninterconnect/it</a>.</li>\n</ol>\n\n<p><strong>Step 4.2 - Users and Post Authors</strong> </p>\n\n<p>You'll want to probably create a note about all the user's from your Standalone installation and map the old user ID's to the new user ID's (from the Multisite installation).</p>\n\n<p>You can simply just create a temporary text file and do something like this:</p>\n\n<pre><code>1 => 4\n8 => 23\n15 => 9\n</code></pre>\n\n<p>The numbers on the left are the ID's from the Standalone installation and the numbers on the right are the ID's on the Multisite installation.</p>\n\n<p>You'll then want to update the <code>post_author</code> column of the <code>wp_posts</code> table to update all of the old user ID's to the new user ID's. Otherwise when view your migrated site from Standalone to Multisite, you're going to be one confused kitten. It's going to say things on your site were posted by random people and probably even people from different sites in your network. This can be catastrophic if overlooked.</p>\n\n<p>For each of the user ID mappings in your text file, you'll want to issue a command much like this into MySQL:</p>\n\n<pre><code>UPDATE wp_posts\nSET post_author = '4'\nWHERE post_author = '1'\n</code></pre>\n\n<ul>\n<li>The line <code>SET post_author = '4'</code> is the new user ID (the user ID from\nthe Multisite installation)</li>\n<li>The line <code>WHERE post_author = '1'</code> is the old user ID (the user ID\nfrom the Standalone installation)</li>\n</ul>\n\n<h2>Step 5 - Users and Usermeta</h2>\n\n<p>I haven't really found a good solution for this step yet. I usually just recreate the users manually in the Multisite installation. </p>\n\n<p>In otherwords, I usually just drop two tables <code>wp_users</code> and <code>wp_usermeta</code>.</p>\n\n<p><em>If anyone would like to improve on this step feel free to edit and add guidance here.</em></p>\n\n<h2>Step 6 - Update Database Table Names</h2>\n\n<p>This step is much like Step 4.</p>\n\n<p>You'll want to map old table names to new table names in the \"<code>standalone</code>\" database on your local Database Server.</p>\n\n<p>This is the step where you will need to know the site ID # from your Multisite installation.</p>\n\n<p><strong>As an example:</strong> If your site ID is <code>15</code>, and your database table prefix use on your Multisite installation is <code>tenp_</code>, then the database table <code>wp_posts</code> would become <code>tenp_15_posts</code>.</p>\n\n<p>Here's the MySQL command you can use to update your database table names:</p>\n\n<pre><code>RENAME TABLE `wp_posts` \nTO `tenp_15_posts`;\n</code></pre>\n\n<ul>\n<li>The first line is the old database table name (the database table name from the Standalone installation)</li>\n<li>The second line is the new database table name (the database table name format to be used in the Multisite installation)</li>\n</ul>\n\n<p>Alternatively, if your database is small enough. You could just export the entire database and open it in a text editor. Then find all & replace. Save it when completed.</p>\n\n<h2>Step 7 - Export and Import</h2>\n\n<p>Once all of the above changes have been made, export the \"<code>standalone</code>\" database from your local Database Server.</p>\n\n<ol>\n<li>Import the exported <code>.sql</code> file into the \"<code>multisite</code>\" database on\nyour local Database Server.</li>\n<li>Export the \"<code>multisite</code>\" database from your local Database Server.</li>\n<li>Drop the current Multisite database tables used for your existing\nMultisite database (not the one on your local Database Server).</li>\n<li>Import the <code>.sql</code> file for your \"<code>multisite</code>\" database you exported\nfrom your local Database Server and import it to your database used\nby your existing Multisite installation (the one you just dropped\nall the tables from). Essentially just replacing the current\nMultisite installation's database with the modified one which\ncontains the newly migrated Standalone site.</li>\n</ol>\n\n<hr>\n\n<p><strong>Moving Uploads files from <code>./wp-content/</code>.</strong></p>\n\n<p>Standalone and Multisite store uploaded files differently. Multisite stores them in <code>./wp-content/sites/{$site_id}/</code>. Make sure you move your uploaded files appropriately as well.</p>\n\n<hr>\n\n<p><strong>Changing the Primary Site:</strong></p>\n\n<p>Look for database table <code>wp_site</code> in your Multisite database. Edit the column <code>id</code> and <code>domain</code> appropriately. </p>\n\n<p>You might need to also edit the <code>site_id</code> column in the <code>wp_blogs</code> table.</p>\n\n<p>Also look in <code>wp-config.php</code> for these lines and once again, adjust them accordingly.</p>\n\n<pre><code>define( 'DOMAIN_CURRENT_SITE', 'www.your-domain.com' );\ndefine( 'SITE_ID_CURRENT_SITE', 1 );\ndefine( 'BLOG_ID_CURRENT_SITE', 1 );\n</code></pre>\n\n<hr>\n\n<p><strong>Useful Links:</strong></p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Moving_WordPress\" rel=\"nofollow noreferrer\">Moving WordPress</a></li>\n<li><a href=\"https://codex.wordpress.org/Migrating_Multiple_Blogs_into_WordPress_3.0_Multisite\" rel=\"nofollow noreferrer\">Migrating Multiple Blogs into WordPress 3.0\nMultisite</a></li>\n</ul>\n\n<hr>\n\n<p><strong>End.</strong></p>\n\n<p><strong>If anything is confusing, please comment and I'll try to clear it up.</strong></p>\n"
},
{
"answer_id": 309866,
"author": "THE WAR OF DESTINY",
"author_id": 126144,
"author_profile": "https://wordpress.stackexchange.com/users/126144",
"pm_score": -1,
"selected": false,
"text": "<p>I followed this tut step by step and successfully migrated 8 sites out of multisite. I am SO grateful for this. Thank you!!!</p>\n\n<p>In my case, I had set up the sites as subdomains using a wildcard subdomain in cPanel. We wanted to keep the sites in their respective subdomains once extracted to single sites. In other words, the urls would not change. This created the following extra steps for us, which I am sharing in case anyone else has a similar set up.</p>\n\n<ol>\n<li>Pause CloudFlare (if you're using it) for the subdomain that you are moving out of multisite.</li>\n<li>Follow the steps in this tutorial to get all of the data out of the site (subdomain).</li>\n<li>Go into WP Network Admin and set the site to \"Archive\".</li>\n<li>Add the subdomain to cPanel (remember, we were using wildcard subdomain in mu - now we need to create a named subdomain record so we have a directory to install to).</li>\n<li>Once this subdomain is set up, go back to the steps in this tutorial and install the new site into the subdirectory.</li>\n<li>Make sure the site is working as expected. If it is, you can go into WP Network Admin and delete the site that you just migrated or leave it a few days in case you need to roll back. </li>\n<li>Turn CloudFlare back on. You're good to go.</li>\n</ol>\n\n<p>Again, I am sharing because this tutorial got me through a really stressful process. Thank you again!</p>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101431/"
] |
I'm fairly new to Wordpress and I'm a little confuse on how to take the database from my local server and replace it with the one on the server on a Wordpress multisite.
I've replace database before from local to server, but it was a multisite.
The step I usually take is:
1. backup the database on the server
2. export local database
3. drop all table on the server database
4. import the local database
5. go to wp\_option
6. change value for siteurl and home to the site url
When I try that, the table on the server is very different from the one on my local.
My local database structure looks like this:
[](https://i.stack.imgur.com/EDSJo.png)
Usually the server database is the same, but not in this case though.
Server database structure:
[](https://i.stack.imgur.com/5itEC.png)
So i'm a little confuse on how to tackle this. Can I still do what I usually do, or is there additional steps I need to take?
Thanks in advance.
Edit: Think I overcomplicated this a bit, I could just create a new database on the server and point the wp\_config.php file to that instead and everything should be good
Edit 2: nope doesn't work like I thought it would. keep getting redirect loop error
Edit 3: I finally got everything to migrate properly all thanks to [@Michael Ecklund](https://wordpress.stackexchange.com/users/9579/michael-ecklund)! Since I was updating the database of the primary page I didn't need to create a new site, but still follow the rest of the [instruction](https://wordpress.stackexchange.com/a/253175/101431) he wrote and it went fairly smooth. A bit of confusion at first, but that was my own lack of knowledge.
Edit 4: Just a FYI, if after doing the database migration and you somehow lost access to the dashboard. Go into your main database and in the \*\_options (in my case the tenp\_options) table and look for an `wp_user_roles` under the option\_name column and change that column name to your site prefix (which in my case is `tenp_`) and you should now be able to access your dashboard again.
|
Merging WordPress Standalone Installation with WordPress Multisite Installation
-------------------------------------------------------------------------------
**Before You Begin:**
1. Create a new site in your Multisite Network, which will be the site
you're migrating from the Standalone installation. (Take note of the site ID #, you'll need it later.)
2. You need to make sure that all of the users from the Standalone
installation, are created and exist in the Multisite installation.
Step 1 - Backup Databases.
--------------------------
Find the directory on your Web Server which the the Standalone copy of WordPress is installed and the directory on your Web Server which the Multisite copy of WordPress is installed and open the `wp-config.php` file of both installations. Locate the PHP constant `DB_NAME`. It contains the name of the database that particular installation of WordPress is using.
1. Backup the Standalone instillation's database.
2. Backup the Multisite installation's database.
Step 2 - Identify the Database Table Prefixes.
----------------------------------------------
*By default the database table prefix is `wp_`.*
If you can't identify the database table prefix just by examining the database. You can look in the base directory of your WordPress installation and open the `wp-config.php` file of the site in question and look for a line like `$table_prefix = 'wp_';`.
**In your situation, it looks like:**
* The Standalone installation's database table prefix is the default of
`wp_`.
* The Multisite installation's database table prefix is custom of
`tenp_`.
Step 3 - Export Databases. Import Into Local Environment.
---------------------------------------------------------
On a local Database Server, create a temporary database for each of these databases. Perhaps to keep things simple, label one database "`standalone`", and the second one "`multisite`".
* Import the Standalone installation's database (which you just
exported) into the "`standalone`" database (which you just created) on
your local Database Server.
* Import the Multisite installation's database (which you just
exported) into the "`multisite`" database (which you just created) on
your local Database Server.
Step 4 - Search and Replace.
----------------------------
This is the step where you would likely replace any necessary URL changes. (http to https), (non-www to www), (add or remove directories from URL), etc.
Perform this task on the "`standalone`" database you created on your local Database Server.
Remember to change things to how you would like them to be in the Multisite installation (the end result).
**For this procedure, you're going to need a Database Tool:**
1. [WP-CLI :: wp search-replace](http://wp-cli.org/commands/search-replace/) which is
all command line.
2. Alternatively, if you prefer a GUI, there's the [Database Search and
Replace Script in PHP by
interconnect/it](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/).
**Step 4.2 - Users and Post Authors**
You'll want to probably create a note about all the user's from your Standalone installation and map the old user ID's to the new user ID's (from the Multisite installation).
You can simply just create a temporary text file and do something like this:
```
1 => 4
8 => 23
15 => 9
```
The numbers on the left are the ID's from the Standalone installation and the numbers on the right are the ID's on the Multisite installation.
You'll then want to update the `post_author` column of the `wp_posts` table to update all of the old user ID's to the new user ID's. Otherwise when view your migrated site from Standalone to Multisite, you're going to be one confused kitten. It's going to say things on your site were posted by random people and probably even people from different sites in your network. This can be catastrophic if overlooked.
For each of the user ID mappings in your text file, you'll want to issue a command much like this into MySQL:
```
UPDATE wp_posts
SET post_author = '4'
WHERE post_author = '1'
```
* The line `SET post_author = '4'` is the new user ID (the user ID from
the Multisite installation)
* The line `WHERE post_author = '1'` is the old user ID (the user ID
from the Standalone installation)
Step 5 - Users and Usermeta
---------------------------
I haven't really found a good solution for this step yet. I usually just recreate the users manually in the Multisite installation.
In otherwords, I usually just drop two tables `wp_users` and `wp_usermeta`.
*If anyone would like to improve on this step feel free to edit and add guidance here.*
Step 6 - Update Database Table Names
------------------------------------
This step is much like Step 4.
You'll want to map old table names to new table names in the "`standalone`" database on your local Database Server.
This is the step where you will need to know the site ID # from your Multisite installation.
**As an example:** If your site ID is `15`, and your database table prefix use on your Multisite installation is `tenp_`, then the database table `wp_posts` would become `tenp_15_posts`.
Here's the MySQL command you can use to update your database table names:
```
RENAME TABLE `wp_posts`
TO `tenp_15_posts`;
```
* The first line is the old database table name (the database table name from the Standalone installation)
* The second line is the new database table name (the database table name format to be used in the Multisite installation)
Alternatively, if your database is small enough. You could just export the entire database and open it in a text editor. Then find all & replace. Save it when completed.
Step 7 - Export and Import
--------------------------
Once all of the above changes have been made, export the "`standalone`" database from your local Database Server.
1. Import the exported `.sql` file into the "`multisite`" database on
your local Database Server.
2. Export the "`multisite`" database from your local Database Server.
3. Drop the current Multisite database tables used for your existing
Multisite database (not the one on your local Database Server).
4. Import the `.sql` file for your "`multisite`" database you exported
from your local Database Server and import it to your database used
by your existing Multisite installation (the one you just dropped
all the tables from). Essentially just replacing the current
Multisite installation's database with the modified one which
contains the newly migrated Standalone site.
---
**Moving Uploads files from `./wp-content/`.**
Standalone and Multisite store uploaded files differently. Multisite stores them in `./wp-content/sites/{$site_id}/`. Make sure you move your uploaded files appropriately as well.
---
**Changing the Primary Site:**
Look for database table `wp_site` in your Multisite database. Edit the column `id` and `domain` appropriately.
You might need to also edit the `site_id` column in the `wp_blogs` table.
Also look in `wp-config.php` for these lines and once again, adjust them accordingly.
```
define( 'DOMAIN_CURRENT_SITE', 'www.your-domain.com' );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );
```
---
**Useful Links:**
* [Moving WordPress](https://codex.wordpress.org/Moving_WordPress)
* [Migrating Multiple Blogs into WordPress 3.0
Multisite](https://codex.wordpress.org/Migrating_Multiple_Blogs_into_WordPress_3.0_Multisite)
---
**End.**
**If anything is confusing, please comment and I'll try to clear it up.**
|
253,155 |
<p>How do I fit a function inside an opening and closing shortcode.</p>
<p>I have this function that displays the post's pdf attachment url</p>
<pre><code>$file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id );
printf( '%s', $full_size); } }
</code></pre>
<p>How would I fit the above code into this...</p>
<pre><code>echo do_shortcode( '[pdf]' . $text_to_be_wrapped_in_shortcode . '[/pdf]' );
</code></pre>
|
[
{
"answer_id": 253159,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 0,
"selected": false,
"text": "<p>Worked it out...</p>\n\n<pre><code><?php $file= get_post_meta( $post->ID, 'teacher-resume-upload' ); $full_size = wp_get_attachment_url( $attachment_id );?>\n<?php echo do_shortcode( '[pdf]' . $full_size . '[/pdf]' ); ?>\n</code></pre>\n"
},
{
"answer_id": 253162,
"author": "Evan",
"author_id": 63098,
"author_profile": "https://wordpress.stackexchange.com/users/63098",
"pm_score": 2,
"selected": true,
"text": "<p>This should work assuming your trying to pass the URL to the PDF short code</p>\n\n<pre><code>$file= get_post_meta( $post->ID, 'teacher-resume-upload' ); \nif ( $file) { \n foreach ( $file as $attachment_id ) { \n $full_size = wp_get_attachment_url( $attachment_id ); \n echo do_shortcode( '[pdf]' . $full_size . '[/pdf]' );\n } \n}\n</code></pre>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253155",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] |
How do I fit a function inside an opening and closing shortcode.
I have this function that displays the post's pdf attachment url
```
$file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id );
printf( '%s', $full_size); } }
```
How would I fit the above code into this...
```
echo do_shortcode( '[pdf]' . $text_to_be_wrapped_in_shortcode . '[/pdf]' );
```
|
This should work assuming your trying to pass the URL to the PDF short code
```
$file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) {
foreach ( $file as $attachment_id ) {
$full_size = wp_get_attachment_url( $attachment_id );
echo do_shortcode( '[pdf]' . $full_size . '[/pdf]' );
}
}
```
|
253,216 |
<p>how can I create non-Wordpress sites on subdomains (map them to directories), when I have an active subdomain-multisite WP installation?</p>
<p>Can I insert some .. exemptions into htaccess or something?</p>
|
[
{
"answer_id": 266673,
"author": "Karthik",
"author_id": 68260,
"author_profile": "https://wordpress.stackexchange.com/users/68260",
"pm_score": 0,
"selected": false,
"text": "<p>Yes. We can add rewrite rule in WordPress root <code>.htaccess</code> to rewrite all requests for a particular subdomain into a subdirectory.\nI could make it work with something like this:</p>\n\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine On\n RewriteBase /\n RewriteCond %{HTTP_HOST} ^sub\\.domain\\.com$\n RewriteRule (.*) sub/directory/index.php [L]\n</IfModule>\n\n# BEGIN WordPress\n # wordpress generated rewrite rules.\n# END WordPress\n</code></pre>\n\n<p>PS:</p>\n\n<ol>\n<li>In above code sub domain and sub directory should be set according to your setup.</li>\n<li>Mentioned Rewrite rule should be set before WordPress rules, so that apache looks at these rules before touching WordPress.</li>\n</ol>\n"
},
{
"answer_id": 266701,
"author": "hwl",
"author_id": 118366,
"author_profile": "https://wordpress.stackexchange.com/users/118366",
"pm_score": 3,
"selected": true,
"text": "<p>The <a href=\"https://codex.wordpress.org/WPMS_Ignore_Some_Subdomains\" rel=\"nofollow noreferrer\">WP Codex gives two examples of excluding a subdirectory from multisite's control.</a></p>\n<ol>\n<li>.htaccess method <a href=\"https://wordpress.stackexchange.com/a/266673/118366\">(as Karthik noted)</a></li>\n<li>Virtual host method</li>\n</ol>\n<h2>.htaccess</h2>\n<p>Being sure to call the sub rewrite BEFORE the rewrite of ww.domain.com to domain.com</p>\n<pre><code>RewriteEngine On\nRewriteBase /\n\nRewriteCond %{HTTP_HOST} subdomain.domain.com\nRewriteCond %{REQUEST_URI} !subdomain/\nRewriteRule ^(.*)$ subdomain/$1 [L]\n\n# Rewrite http://www.domain.com to domain.com\nRewriteCond %{HTTP_HOST} ^www.(.*)\nRewriteRule ^(.*) http://%1/$1 [R,L]\n</code></pre>\n<p>This answer to issues with this covers the hierarchical nature of .htaccess to keep in mind: <a href=\"https://wordpress.stackexchange.com/a/20274/118366\">https://wordpress.stackexchange.com/a/20274/118366</a></p>\n<h2>Virtual Host</h2>\n<p>Quoting the linked Codex page on this:</p>\n<blockquote>\n<p>If you are able to configure your VirtualHost file this may be the best method. It provides the ability to serve the subdomain out of any directory on your server.</p>\n<p>To do this you simply need to make sure that the domain you do not want WPMS to handle is loaded before the WPMS primary domain that uses the wildcard.</p>\n</blockquote>\n"
}
] |
2017/01/19
|
[
"https://wordpress.stackexchange.com/questions/253216",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38435/"
] |
how can I create non-Wordpress sites on subdomains (map them to directories), when I have an active subdomain-multisite WP installation?
Can I insert some .. exemptions into htaccess or something?
|
The [WP Codex gives two examples of excluding a subdirectory from multisite's control.](https://codex.wordpress.org/WPMS_Ignore_Some_Subdomains)
1. .htaccess method [(as Karthik noted)](https://wordpress.stackexchange.com/a/266673/118366)
2. Virtual host method
.htaccess
---------
Being sure to call the sub rewrite BEFORE the rewrite of ww.domain.com to domain.com
```
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} subdomain.domain.com
RewriteCond %{REQUEST_URI} !subdomain/
RewriteRule ^(.*)$ subdomain/$1 [L]
# Rewrite http://www.domain.com to domain.com
RewriteCond %{HTTP_HOST} ^www.(.*)
RewriteRule ^(.*) http://%1/$1 [R,L]
```
This answer to issues with this covers the hierarchical nature of .htaccess to keep in mind: <https://wordpress.stackexchange.com/a/20274/118366>
Virtual Host
------------
Quoting the linked Codex page on this:
>
> If you are able to configure your VirtualHost file this may be the best method. It provides the ability to serve the subdomain out of any directory on your server.
>
>
> To do this you simply need to make sure that the domain you do not want WPMS to handle is loaded before the WPMS primary domain that uses the wildcard.
>
>
>
|
253,226 |
<p>I have an attachment page for post images, so that when I click on the thumbnail (on the front end) it takes the user to the attachment page for that image, how would I do the same for pdf files, so that when I click on the direct link to the pdf on the front end to redirects to the pdf attachment page?</p>
<pre><code><?php if ( wp_attachment_is_image( $post->id ) ) : $att_image = wp_get_attachment_image_src( $post->id, "full"); ?>
<center>
<p class="full-attachment">
<?php /* <a href="<?php echo wp_get_attachment_url($post->id); ?>" title="<?php the_title(); ?>" rel="attachment"> */ ?>
<img src="<?php echo $att_image[0];?>" width="<?php echo $att_image[1];?>" height="<?php echo $att_image[2];?>" class="attachment-full" alt="<?php $post->post_title; ?>" />
<?php /* </a> */ ?>
</p>
</center>
<?php else : ?>
<a href="<?php echo wp_get_attachment_url($post->ID) ?>" title="<?php echo wp_specialchars( get_the_title($post->ID), 1 ) ?>" rel="attachment">
<?php echo basename($post->guid) ?>
</a>
<?php endif; ?>
</code></pre>
<p>This is my theme file's single.php</p>
<pre><code><?php $file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id ); printf( '<a href="%s">download</a>', $full_size); } } ?>
</code></pre>
|
[
{
"answer_id": 253291,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>From the <a href=\"https://developer.wordpress.org/reference/functions/get_attachment_template/\" rel=\"nofollow noreferrer\"><code>get_attachment_template()</code></a> we can see how the attachment's <em>template hierarchy</em> is constructed.</p>\n\n<p>Let's check out some examples:</p>\n\n<ul>\n<li><p>For a <em>pdf</em> file, with the <code>applicaton/pdf</code> mime type it's:</p>\n\n<pre><code>- application-pdf.php\n- pdf.php\n- application.php\n- attachment.php\n</code></pre></li>\n<li><p>For a <em>jpeg</em> image with the <code>image/jpeg</code> mime type it's: </p>\n\n<pre><code>- image-jpeg.php\n- jpeg.php\n- image.php\n- attachment.php\n</code></pre></li>\n<li><p>For a <em>png</em> image with the <code>image/png</code> mime type it's: </p>\n\n<pre><code>- image-png.php\n- png.php\n- image.php\n- attachment.php\n</code></pre></li>\n<li><p>For an <em>mp3</em> audio file with the <code>audio/mpeg</code> mime type it's: </p>\n\n<pre><code>- audio-mpeg.php\n- mpeg.php\n- audio.php\n- attachment.php\n</code></pre></li>\n</ul>\n\n<p>If none of these files exists in the current theme directory, then the fallbacks are (in order):</p>\n\n<pre><code>- {custom post template}.php\n- single-attachment-{slug}.php\n- single-attachment.php\n- single.php\n- singular.php\n- index.php\n</code></pre>\n\n<p>I added the <code>{custom post template}.php</code> here, because we can add a postmeta row for the <code>_wp_page_template</code> key for a given attachment, with the template filename as a meta value.</p>\n\n<p>If we check out the Codex on <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#attachment\" rel=\"nofollow noreferrer\">Template Hierarchy</a>, then it seems to be missing some fallback options.</p>\n\n<p>Then if we want to modify the <em>embed template</em> for attachments, then we can e.g. use <code>embed-attachment.php</code> or <code>embed.php</code> </p>\n"
},
{
"answer_id": 256866,
"author": "Marinus Klasen",
"author_id": 113579,
"author_profile": "https://wordpress.stackexchange.com/users/113579",
"pm_score": 2,
"selected": false,
"text": "<p>This should do the trick:</p>\n\n<pre><code><?php if ( get_post_mime_type($post->ID) == 'application/pdf' ) : ?>\n <object data=\"<?php echo wp_get_attachment_url($post->ID); ?>\" type=\"application/pdf\" width=\"100%\" height=\"1000px\"><a href=\"<?php echo wp_get_attachment_url($post->ID); ?>\">Download the PDF here.</a></object>\n<?php endif; ?>\n</code></pre>\n\n<p><code>get_post_mime_type()</code> tells your what the type of your attachment is - kinda like the <code>wp_attachment_is_image($post->ID)</code>. If it matches PDF then the code is being executed. </p>\n\n<p>When you run this outside of the <code>attachment.php</code> template file you should wrap the code in <code><?php if is_attachment(): ?> <?php endif; ?></code>.</p>\n"
},
{
"answer_id": 401078,
"author": "Matthew McVickar",
"author_id": 8559,
"author_profile": "https://wordpress.stackexchange.com/users/8559",
"pm_score": 2,
"selected": true,
"text": "<p>You can use <code>pdf.php</code> or a number of other specially-named template files <a href=\"https://wordpress.stackexchange.com/a/253291/8559\">as described birgire's answer</a> to show an attachment page specifically for PDFs, or use a generic <code>attachment.php</code> page that includes conditional statements for the type of attachment (like the code in your question does).</p>\n<h2>Potential Conflict with Yoast SEO Plugin</h2>\n<p>Note that attachment template pages may not work if you have the Yoast SEO plugin installed. The default setting under <strong>Yoast SEO › Search Appearance › Media</strong> is to 'Redirect attachment URLs to the attachment itself,' which will override any attachment page template and directly link to the PDF, image file, or whatever you've uploaded.</p>\n<h2>How to Use Attachment Page Only for PDFs and Redirect Other Attachment Types Directly to their Files</h2>\n<p>Bonus: If you <em>only</em> want to show PDF attachment pages and redirect everything else to the attachment file, here's some code to do that. (You'd put this in your <code>functions.php</code> file.)</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Redirect media attachment URLs to the attachment itself *unless* it's a PDF.\n * See details: https://wordpress.stackexchange.com/questions/253226/\n */\nadd_action(\n 'template_redirect',\n function() {\n // Exit if this is not an attachment page.\n if ( ! is_attachment() ) {\n return;\n }\n\n // Exit (do nothing; do not redirect; use\n // the pdf.php attachment template page) \n // if this is a PDF attachment page.\n if ( false !== stripos( get_post_mime_type(), 'pdf' ) ) {\n return;\n }\n\n // Redirect all other attachment pages to\n // their file. Use code '301' to indicate\n // this is a permanent redirect.\n if ( wp_get_attachment_url() ) {\n wp_safe_redirect( wp_get_attachment_url(), '301' );\n }\n }\n);\n</code></pre>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253226",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] |
I have an attachment page for post images, so that when I click on the thumbnail (on the front end) it takes the user to the attachment page for that image, how would I do the same for pdf files, so that when I click on the direct link to the pdf on the front end to redirects to the pdf attachment page?
```
<?php if ( wp_attachment_is_image( $post->id ) ) : $att_image = wp_get_attachment_image_src( $post->id, "full"); ?>
<center>
<p class="full-attachment">
<?php /* <a href="<?php echo wp_get_attachment_url($post->id); ?>" title="<?php the_title(); ?>" rel="attachment"> */ ?>
<img src="<?php echo $att_image[0];?>" width="<?php echo $att_image[1];?>" height="<?php echo $att_image[2];?>" class="attachment-full" alt="<?php $post->post_title; ?>" />
<?php /* </a> */ ?>
</p>
</center>
<?php else : ?>
<a href="<?php echo wp_get_attachment_url($post->ID) ?>" title="<?php echo wp_specialchars( get_the_title($post->ID), 1 ) ?>" rel="attachment">
<?php echo basename($post->guid) ?>
</a>
<?php endif; ?>
```
This is my theme file's single.php
```
<?php $file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id ); printf( '<a href="%s">download</a>', $full_size); } } ?>
```
|
You can use `pdf.php` or a number of other specially-named template files [as described birgire's answer](https://wordpress.stackexchange.com/a/253291/8559) to show an attachment page specifically for PDFs, or use a generic `attachment.php` page that includes conditional statements for the type of attachment (like the code in your question does).
Potential Conflict with Yoast SEO Plugin
----------------------------------------
Note that attachment template pages may not work if you have the Yoast SEO plugin installed. The default setting under **Yoast SEO › Search Appearance › Media** is to 'Redirect attachment URLs to the attachment itself,' which will override any attachment page template and directly link to the PDF, image file, or whatever you've uploaded.
How to Use Attachment Page Only for PDFs and Redirect Other Attachment Types Directly to their Files
----------------------------------------------------------------------------------------------------
Bonus: If you *only* want to show PDF attachment pages and redirect everything else to the attachment file, here's some code to do that. (You'd put this in your `functions.php` file.)
```php
/**
* Redirect media attachment URLs to the attachment itself *unless* it's a PDF.
* See details: https://wordpress.stackexchange.com/questions/253226/
*/
add_action(
'template_redirect',
function() {
// Exit if this is not an attachment page.
if ( ! is_attachment() ) {
return;
}
// Exit (do nothing; do not redirect; use
// the pdf.php attachment template page)
// if this is a PDF attachment page.
if ( false !== stripos( get_post_mime_type(), 'pdf' ) ) {
return;
}
// Redirect all other attachment pages to
// their file. Use code '301' to indicate
// this is a permanent redirect.
if ( wp_get_attachment_url() ) {
wp_safe_redirect( wp_get_attachment_url(), '301' );
}
}
);
```
|
253,235 |
<p>I am trying to display the numerical post order ranking on the home page, however, I am using template_parts and am not aware of how to do this when the html is separated from the wordpress loop.</p>
<p>Here's what I want to see:</p>
<p><a href="https://i.stack.imgur.com/bO3EC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bO3EC.png" alt="ranking concept"></a></p>
<p>Here is my loop in <code>index.php</code></p>
<pre><code><div class="most-recent-feed">
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) : ?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
$post_ranking = 1;
/* Start the Loop */
while ( have_posts() ) : the_post();
?> <h1> <?php echo $post_ranking ?> </h1> <?php
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
wp_reset_query();
?>
</div>
</code></pre>
<p>And here is my relevant html in <code>template_parts/content.php</code> (note the comment where the ranking number should be placed:</p>
<pre><code><div class="album-dark-overlay play">
<div class="ranking-triangle">
<!-- Ranking number should be placed here -->
</div>
<div id="<?php echo $youtube_id ?>" data-youtube-id="<?php echo $youtube_id ?>" class="media-circle">
<i class="icon ion-ios-play"></i><i class="icon ion-pause"></i>
</div>
</div>
</code></pre>
|
[
{
"answer_id": 253242,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": -1,
"selected": false,
"text": "<p>There are two ways I suggest you do that:</p>\n\n<ul>\n<li>You can store the post rankings in your database <code>wp_postmeta</code> or any table of your choice, and then retrieve the value via <code>WP_QUERY</code> or any of your choice, which will then be <code>echoed</code> in your desired location.</li>\n</ul>\n\n<p><strong>OR</strong></p>\n\n<ul>\n<li>You can use <code>PHP for</code> loop. Get the length of the posts <code>(posts_per_page)</code> and then iterate through each of your result, which will then echo the ranking based on the first-second-third-fourth etc.</li>\n</ul>\n\n<p>Here's an example:</p>\n\n<pre><code>// Get the length of the items (which is determined by the number you enter in 'posts_per_page'\n$loop_length = 6 // using this as an example\nfor( $i = 0; $i <= $loop_length; $i++ ) {\n echo $i;\n}\n// Your result will be 1, 2, 3, 4, 5, 6.\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 253309,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>It is not straightforward to pass a variable to a template part. However, when you are in a loop, WP has <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Properties\" rel=\"nofollow noreferrer\">a counter called <code>current_post</code></a> that you can use in this way in your template part:</p>\n\n<pre><code>global $post;\n$ranking = $post->$current_post + 1; // +1 because the counter starts at 0\n</code></pre>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253235",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105532/"
] |
I am trying to display the numerical post order ranking on the home page, however, I am using template\_parts and am not aware of how to do this when the html is separated from the wordpress loop.
Here's what I want to see:
[](https://i.stack.imgur.com/bO3EC.png)
Here is my loop in `index.php`
```
<div class="most-recent-feed">
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) : ?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
$post_ranking = 1;
/* Start the Loop */
while ( have_posts() ) : the_post();
?> <h1> <?php echo $post_ranking ?> </h1> <?php
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
wp_reset_query();
?>
</div>
```
And here is my relevant html in `template_parts/content.php` (note the comment where the ranking number should be placed:
```
<div class="album-dark-overlay play">
<div class="ranking-triangle">
<!-- Ranking number should be placed here -->
</div>
<div id="<?php echo $youtube_id ?>" data-youtube-id="<?php echo $youtube_id ?>" class="media-circle">
<i class="icon ion-ios-play"></i><i class="icon ion-pause"></i>
</div>
</div>
```
|
It is not straightforward to pass a variable to a template part. However, when you are in a loop, WP has [a counter called `current_post`](https://codex.wordpress.org/Class_Reference/WP_Query#Properties) that you can use in this way in your template part:
```
global $post;
$ranking = $post->$current_post + 1; // +1 because the counter starts at 0
```
|
253,239 |
<p>I would like to make my pagination for single post look like this:</p>
<p><a href="https://i.stack.imgur.com/f2kJe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f2kJe.jpg" alt="pagination with next, prev and links in between and also disabled"></a></p>
<p>and <strong>not</strong> like that.....
<a href="https://i.stack.imgur.com/PCSlu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PCSlu.jpg" alt="current pagination"></a></p>
<p>I am using wordpress and for pagination in single post i using the quicktag. Theme is MH Magazine liteVersion: 2.5.3</p>
|
[
{
"answer_id": 253242,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": -1,
"selected": false,
"text": "<p>There are two ways I suggest you do that:</p>\n\n<ul>\n<li>You can store the post rankings in your database <code>wp_postmeta</code> or any table of your choice, and then retrieve the value via <code>WP_QUERY</code> or any of your choice, which will then be <code>echoed</code> in your desired location.</li>\n</ul>\n\n<p><strong>OR</strong></p>\n\n<ul>\n<li>You can use <code>PHP for</code> loop. Get the length of the posts <code>(posts_per_page)</code> and then iterate through each of your result, which will then echo the ranking based on the first-second-third-fourth etc.</li>\n</ul>\n\n<p>Here's an example:</p>\n\n<pre><code>// Get the length of the items (which is determined by the number you enter in 'posts_per_page'\n$loop_length = 6 // using this as an example\nfor( $i = 0; $i <= $loop_length; $i++ ) {\n echo $i;\n}\n// Your result will be 1, 2, 3, 4, 5, 6.\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 253309,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>It is not straightforward to pass a variable to a template part. However, when you are in a loop, WP has <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Properties\" rel=\"nofollow noreferrer\">a counter called <code>current_post</code></a> that you can use in this way in your template part:</p>\n\n<pre><code>global $post;\n$ranking = $post->$current_post + 1; // +1 because the counter starts at 0\n</code></pre>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253239",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111342/"
] |
I would like to make my pagination for single post look like this:
[](https://i.stack.imgur.com/f2kJe.jpg)
and **not** like that.....
[](https://i.stack.imgur.com/PCSlu.jpg)
I am using wordpress and for pagination in single post i using the quicktag. Theme is MH Magazine liteVersion: 2.5.3
|
It is not straightforward to pass a variable to a template part. However, when you are in a loop, WP has [a counter called `current_post`](https://codex.wordpress.org/Class_Reference/WP_Query#Properties) that you can use in this way in your template part:
```
global $post;
$ranking = $post->$current_post + 1; // +1 because the counter starts at 0
```
|
253,245 |
<p>I just migrated my ecommerce website (www.getfitkart.com) from shared hosting to Linode. Now only the home page is working but the other pages are not getting served. I am getting the following error on all other pages like say, <a href="http://www.getfitkart.com/privacy-policy/" rel="noreferrer">http://www.getfitkart.com/privacy-policy/</a></p>
<blockquote>
<p>Not Found<br/>
The requested URL /privacy-policy/ was not found on this server.</p>
</blockquote>
<p>My .htaccess file:<br/></p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code></pre>
<p>Any help will be greatly appreciated.</p>
|
[
{
"answer_id": 253246,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 4,
"selected": false,
"text": "<p>Go to settings->permalinks and click on save button to rewrite flush. And then empty your browser cache. It'll work hopefully.</p>\n"
},
{
"answer_id": 253758,
"author": "Najeeb",
"author_id": 43567,
"author_profile": "https://wordpress.stackexchange.com/users/43567",
"pm_score": 4,
"selected": true,
"text": "<p>I found the solution here:</p>\n\n<p><a href=\"https://www.digitalocean.com/community/questions/wordpress-permalinks-not-working-on-ubuntu-14-04\" rel=\"noreferrer\">https://www.digitalocean.com/community/questions/wordpress-permalinks-not-working-on-ubuntu-14-04</a></p>\n\n<p>The thing is that we need to allow the override <em>all</em> option in httpd.conf (location: /etc/httpd/conf/httpd.conf) for your specific hosting directory.</p>\n"
},
{
"answer_id": 310640,
"author": "afojet",
"author_id": 148182,
"author_profile": "https://wordpress.stackexchange.com/users/148182",
"pm_score": 1,
"selected": false,
"text": "<p>Dear friend after moving site : go to your phone admin \nThen choose your database.\nClick on wp-option\nChange raw 25 to 500\nChange site url : <a href=\"http://www.yourwebsite.com\" rel=\"nofollow noreferrer\">http://www.yourwebsite.com</a>\nsearch -- path : change path of your upload</p>\n\n<p>Save it\nLogin your site: www.yoursitename.com/wp-admin\nGo to settings \nThen go to Permalink\nDo not change anything\nJust Save it.</p>\n\n<p>Now try your all page.</p>\n"
},
{
"answer_id": 325384,
"author": "GCL",
"author_id": 140232,
"author_profile": "https://wordpress.stackexchange.com/users/140232",
"pm_score": 3,
"selected": false,
"text": "<p>Sometimes on a new server it's just the rewrite module missing from Apache config.</p>\n\n<pre><code>sudo a2enmod rewrite\nsudo service apache2 restart\n</code></pre>\n"
},
{
"answer_id": 345077,
"author": "Rajeev Shrestha",
"author_id": 173477,
"author_profile": "https://wordpress.stackexchange.com/users/173477",
"pm_score": 3,
"selected": false,
"text": "<p>Solved this problem on Linux Mint 19 / PHP Version 7.2.19-0ubuntu0.18.04.1 by changing: </p>\n\n<pre><code><Directory /var/www/>\n Options Indexes FollowSymLinks\n AllowOverride None\n Require all granted\n</Directory> \n</code></pre>\n\n<p>to: </p>\n\n<pre><code><Directory /var/www/>\n Options Indexes FollowSymLinks\n AllowOverride All\n Require all granted\n</Directory> \n</code></pre>\n\n<p>in /etc/apache2/apache2.conf.</p>\n\n<p>Hope this helps!</p>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253245",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43567/"
] |
I just migrated my ecommerce website (www.getfitkart.com) from shared hosting to Linode. Now only the home page is working but the other pages are not getting served. I am getting the following error on all other pages like say, <http://www.getfitkart.com/privacy-policy/>
>
> Not Found
>
> The requested URL /privacy-policy/ was not found on this server.
>
>
>
My .htaccess file:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
```
Any help will be greatly appreciated.
|
I found the solution here:
<https://www.digitalocean.com/community/questions/wordpress-permalinks-not-working-on-ubuntu-14-04>
The thing is that we need to allow the override *all* option in httpd.conf (location: /etc/httpd/conf/httpd.conf) for your specific hosting directory.
|
253,270 |
<p>I have a lot of 404s on posts without /%category%/ (I have change permalink structure). I have noticed that if I put /anything/ in 404 link as category I'll end up in the right post.
How can I solve it? I have around 25k 404s in google console and I need a bulk solution. </p>
<p>My thoughts are either to do it in htaccess or in 404.php (preferably). I was thinking to check request in 404.php and if it misses /category/ just to insert any word and make a new request toward WP to resolve the post.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 253271,
"author": "Ravi Shinde",
"author_id": 99294,
"author_profile": "https://wordpress.stackexchange.com/users/99294",
"pm_score": 0,
"selected": false,
"text": "<p>Use Redirection plugin - <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/redirection/</a></p>\n\n<p>You can set 301 redirection for all your 404 urls from WP admin itself. You can also bulk import urls from csv file.</p>\n\n<p>This way you can tell google that those urls doesn't exist and permanently moved, eventually those console errors will go away.</p>\n"
},
{
"answer_id": 253311,
"author": "klo",
"author_id": 78008,
"author_profile": "https://wordpress.stackexchange.com/users/78008",
"pm_score": 3,
"selected": true,
"text": "<p>Ok, resolved it in 404.php</p>\n\n<pre><code><?php \n\n$klo_link = $_SERVER['REQUEST_URI']; \nif (preg_match(\"/^\\/[a-zA-Z0-9\\-\\_]+\\/$/\", $klo_link)) { \n//echo \"A match was found. \\n\"; \n//echo $klo_link; \nheader(\"HTTP/1.1 301 Moved Permanently\"); \nheader(\"Location: \".get_bloginfo('url').\"/a\".$klo_link); \nexit();\n }else { \nget_header();\n}\n</code></pre>\n\n<p>Put that at the beginning of the 404.ph</p>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253270",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78008/"
] |
I have a lot of 404s on posts without /%category%/ (I have change permalink structure). I have noticed that if I put /anything/ in 404 link as category I'll end up in the right post.
How can I solve it? I have around 25k 404s in google console and I need a bulk solution.
My thoughts are either to do it in htaccess or in 404.php (preferably). I was thinking to check request in 404.php and if it misses /category/ just to insert any word and make a new request toward WP to resolve the post.
Any thoughts?
|
Ok, resolved it in 404.php
```
<?php
$klo_link = $_SERVER['REQUEST_URI'];
if (preg_match("/^\/[a-zA-Z0-9\-\_]+\/$/", $klo_link)) {
//echo "A match was found. \n";
//echo $klo_link;
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".get_bloginfo('url')."/a".$klo_link);
exit();
}else {
get_header();
}
```
Put that at the beginning of the 404.ph
|
253,274 |
<p>I'm seeing an error while trying to change the colours of a theme:</p>
<pre><code>Notice: Use of undefined constant FS_CHMOD_DIR - assumed 'FS_CHMOD_DIR' in
/var/www/vhosts/xxx/wp-content/themes/consulting/inc/print_styles.php on line 141
</code></pre>
<p>The theme creator has given me the following advice, but cannot provide any further detail:</p>
<blockquote>
<p>Please contact your hosting provider team and ask to enable (set up)
PHP FILE extension in your site. It will solve the problem.</p>
</blockquote>
<p>I manage my server, but I have also been in contact with my hosting provider, and neither of us can figure out what needs to be done.</p>
<p>the closest we can find to PHP FILE is the fileinfo extension, which is already installed:</p>
<pre><code>[root]# php -m | grep file
fileinfo
</code></pre>
<p>Can anyone shed any light on this?</p>
|
[
{
"answer_id": 253277,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>It's really quite simple. The theme author is using a constant that you can put in <code>wp-config.php</code>, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning</p>\n\n<p><a href=\"https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions</a></p>\n\n<blockquote>\n <h3>Override of default file permissions</h3>\n \n <p>The FS_CHMOD_DIR and\n FS_CHMOD_FILE define statements allow override of default file\n permissions. These two variables were developed in response to the\n problem of the core update function failing with hosts running under\n suexec. If a host uses restrictive file permissions (e.g. 400) for all\n user files, and refuses to access files which have group or world\n permissions set, these definitions could solve the problem. Note that\n the '0755' is an octal value. Octal values must be prefixed with a 0\n and are not delineated with single quotes ('). See Also: Changing File\n Permissions</p>\n</blockquote>\n\n<h2>FAQ</h2>\n\n<h3>So Who's to Blame?</h3>\n\n<p>The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.</p>\n\n<p>The check is an easy thing to do:</p>\n\n<pre><code>$chmod_dir = ( 0755 & ~ umask() );\nif ( defined( 'FS_CHMOD_DIR' ) ) {\n $chmod_dir = FS_CHMOD_DIR;\n}\n</code></pre>\n\n<p>You use a variable, give it a default variable, then assign the constant to it if it exists.</p>\n\n<h3>What about this file PHP extension?</h3>\n\n<p>It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )</p>\n\n<h3>Is all of this above board?</h3>\n\n<p>Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.</p>\n\n<p>I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder )</p>\n"
},
{
"answer_id": 406106,
"author": "r_D",
"author_id": 222544,
"author_profile": "https://wordpress.stackexchange.com/users/222544",
"pm_score": 0,
"selected": false,
"text": "<p>I faced the same issue, it was due to the permissions of <code>/var/www/html/*</code> files and folders.</p>\n<p>It was owned by root, changed the owner to <code>www-data:www-data</code></p>\n<pre><code>cd /var/www/html\nsudo chown -R www-data:www-data *\n</code></pre>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253274",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111367/"
] |
I'm seeing an error while trying to change the colours of a theme:
```
Notice: Use of undefined constant FS_CHMOD_DIR - assumed 'FS_CHMOD_DIR' in
/var/www/vhosts/xxx/wp-content/themes/consulting/inc/print_styles.php on line 141
```
The theme creator has given me the following advice, but cannot provide any further detail:
>
> Please contact your hosting provider team and ask to enable (set up)
> PHP FILE extension in your site. It will solve the problem.
>
>
>
I manage my server, but I have also been in contact with my hosting provider, and neither of us can figure out what needs to be done.
the closest we can find to PHP FILE is the fileinfo extension, which is already installed:
```
[root]# php -m | grep file
fileinfo
```
Can anyone shed any light on this?
|
It's really quite simple. The theme author is using a constant that you can put in `wp-config.php`, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning
<https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions>
>
> ### Override of default file permissions
>
>
> The FS\_CHMOD\_DIR and
> FS\_CHMOD\_FILE define statements allow override of default file
> permissions. These two variables were developed in response to the
> problem of the core update function failing with hosts running under
> suexec. If a host uses restrictive file permissions (e.g. 400) for all
> user files, and refuses to access files which have group or world
> permissions set, these definitions could solve the problem. Note that
> the '0755' is an octal value. Octal values must be prefixed with a 0
> and are not delineated with single quotes ('). See Also: Changing File
> Permissions
>
>
>
FAQ
---
### So Who's to Blame?
The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.
The check is an easy thing to do:
```
$chmod_dir = ( 0755 & ~ umask() );
if ( defined( 'FS_CHMOD_DIR' ) ) {
$chmod_dir = FS_CHMOD_DIR;
}
```
You use a variable, give it a default variable, then assign the constant to it if it exists.
### What about this file PHP extension?
It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )
### Is all of this above board?
Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.
I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder )
|
253,278 |
<p>When user created URL comes as <strong>www.sitename.com/user/username</strong></p>
<p>I want to change to<br>
<strong>www.sitename.com/username</strong> (Remove User from URL)</p>
<p>How can I do this </p>
|
[
{
"answer_id": 253277,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>It's really quite simple. The theme author is using a constant that you can put in <code>wp-config.php</code>, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning</p>\n\n<p><a href=\"https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions</a></p>\n\n<blockquote>\n <h3>Override of default file permissions</h3>\n \n <p>The FS_CHMOD_DIR and\n FS_CHMOD_FILE define statements allow override of default file\n permissions. These two variables were developed in response to the\n problem of the core update function failing with hosts running under\n suexec. If a host uses restrictive file permissions (e.g. 400) for all\n user files, and refuses to access files which have group or world\n permissions set, these definitions could solve the problem. Note that\n the '0755' is an octal value. Octal values must be prefixed with a 0\n and are not delineated with single quotes ('). See Also: Changing File\n Permissions</p>\n</blockquote>\n\n<h2>FAQ</h2>\n\n<h3>So Who's to Blame?</h3>\n\n<p>The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.</p>\n\n<p>The check is an easy thing to do:</p>\n\n<pre><code>$chmod_dir = ( 0755 & ~ umask() );\nif ( defined( 'FS_CHMOD_DIR' ) ) {\n $chmod_dir = FS_CHMOD_DIR;\n}\n</code></pre>\n\n<p>You use a variable, give it a default variable, then assign the constant to it if it exists.</p>\n\n<h3>What about this file PHP extension?</h3>\n\n<p>It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )</p>\n\n<h3>Is all of this above board?</h3>\n\n<p>Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.</p>\n\n<p>I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder )</p>\n"
},
{
"answer_id": 406106,
"author": "r_D",
"author_id": 222544,
"author_profile": "https://wordpress.stackexchange.com/users/222544",
"pm_score": 0,
"selected": false,
"text": "<p>I faced the same issue, it was due to the permissions of <code>/var/www/html/*</code> files and folders.</p>\n<p>It was owned by root, changed the owner to <code>www-data:www-data</code></p>\n<pre><code>cd /var/www/html\nsudo chown -R www-data:www-data *\n</code></pre>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253278",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111277/"
] |
When user created URL comes as **www.sitename.com/user/username**
I want to change to
**www.sitename.com/username** (Remove User from URL)
How can I do this
|
It's really quite simple. The theme author is using a constant that you can put in `wp-config.php`, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning
<https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions>
>
> ### Override of default file permissions
>
>
> The FS\_CHMOD\_DIR and
> FS\_CHMOD\_FILE define statements allow override of default file
> permissions. These two variables were developed in response to the
> problem of the core update function failing with hosts running under
> suexec. If a host uses restrictive file permissions (e.g. 400) for all
> user files, and refuses to access files which have group or world
> permissions set, these definitions could solve the problem. Note that
> the '0755' is an octal value. Octal values must be prefixed with a 0
> and are not delineated with single quotes ('). See Also: Changing File
> Permissions
>
>
>
FAQ
---
### So Who's to Blame?
The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.
The check is an easy thing to do:
```
$chmod_dir = ( 0755 & ~ umask() );
if ( defined( 'FS_CHMOD_DIR' ) ) {
$chmod_dir = FS_CHMOD_DIR;
}
```
You use a variable, give it a default variable, then assign the constant to it if it exists.
### What about this file PHP extension?
It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )
### Is all of this above board?
Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.
I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder )
|
253,283 |
<p>when i install a theme it appears to be completely different and doenst shows contents which are supposed to be there. And nothing happens if a do changes from dashboard appearance and customize. kindly help!
[![see here][1]][1]</p>
<p>[![?][2]][2]</p>
<p><a href="https://i.stack.imgur.com/6MQE4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6MQE4.png" alt="?"></a></p>
<p><a href="https://i.stack.imgur.com/WmLxB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WmLxB.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 253277,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>It's really quite simple. The theme author is using a constant that you can put in <code>wp-config.php</code>, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning</p>\n\n<p><a href=\"https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions</a></p>\n\n<blockquote>\n <h3>Override of default file permissions</h3>\n \n <p>The FS_CHMOD_DIR and\n FS_CHMOD_FILE define statements allow override of default file\n permissions. These two variables were developed in response to the\n problem of the core update function failing with hosts running under\n suexec. If a host uses restrictive file permissions (e.g. 400) for all\n user files, and refuses to access files which have group or world\n permissions set, these definitions could solve the problem. Note that\n the '0755' is an octal value. Octal values must be prefixed with a 0\n and are not delineated with single quotes ('). See Also: Changing File\n Permissions</p>\n</blockquote>\n\n<h2>FAQ</h2>\n\n<h3>So Who's to Blame?</h3>\n\n<p>The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.</p>\n\n<p>The check is an easy thing to do:</p>\n\n<pre><code>$chmod_dir = ( 0755 & ~ umask() );\nif ( defined( 'FS_CHMOD_DIR' ) ) {\n $chmod_dir = FS_CHMOD_DIR;\n}\n</code></pre>\n\n<p>You use a variable, give it a default variable, then assign the constant to it if it exists.</p>\n\n<h3>What about this file PHP extension?</h3>\n\n<p>It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )</p>\n\n<h3>Is all of this above board?</h3>\n\n<p>Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.</p>\n\n<p>I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder )</p>\n"
},
{
"answer_id": 406106,
"author": "r_D",
"author_id": 222544,
"author_profile": "https://wordpress.stackexchange.com/users/222544",
"pm_score": 0,
"selected": false,
"text": "<p>I faced the same issue, it was due to the permissions of <code>/var/www/html/*</code> files and folders.</p>\n<p>It was owned by root, changed the owner to <code>www-data:www-data</code></p>\n<pre><code>cd /var/www/html\nsudo chown -R www-data:www-data *\n</code></pre>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253283",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111374/"
] |
when i install a theme it appears to be completely different and doenst shows contents which are supposed to be there. And nothing happens if a do changes from dashboard appearance and customize. kindly help!
[![see here][1]][1]
[![?][2]][2]
[](https://i.stack.imgur.com/6MQE4.png)
[](https://i.stack.imgur.com/WmLxB.png)
|
It's really quite simple. The theme author is using a constant that you can put in `wp-config.php`, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning
<https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions>
>
> ### Override of default file permissions
>
>
> The FS\_CHMOD\_DIR and
> FS\_CHMOD\_FILE define statements allow override of default file
> permissions. These two variables were developed in response to the
> problem of the core update function failing with hosts running under
> suexec. If a host uses restrictive file permissions (e.g. 400) for all
> user files, and refuses to access files which have group or world
> permissions set, these definitions could solve the problem. Note that
> the '0755' is an octal value. Octal values must be prefixed with a 0
> and are not delineated with single quotes ('). See Also: Changing File
> Permissions
>
>
>
FAQ
---
### So Who's to Blame?
The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.
The check is an easy thing to do:
```
$chmod_dir = ( 0755 & ~ umask() );
if ( defined( 'FS_CHMOD_DIR' ) ) {
$chmod_dir = FS_CHMOD_DIR;
}
```
You use a variable, give it a default variable, then assign the constant to it if it exists.
### What about this file PHP extension?
It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )
### Is all of this above board?
Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.
I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder )
|
253,290 |
<p>I have this php file on the root directory, and i seen this example for inserting post from external php file
but for some reason it doesn't work for me, <code>wp_insert_post()</code> always returns <code>0</code></p>
<p>So whats the problem ? and how i can fix it?</p>
<p>I'm trying to build a Cron Job file to insert new posts from XML file In the end</p>
<p>Thank you!</p>
<p>CronJob.php:</p>
<pre><code><?php
require_once './wp-load.php';
$new_post = array(
'post_title' => 'My New Post',
'post_content' => 'Lorem ipsum dolor sit amet...',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => '3',
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
var_dump($post_id); die; // Return int(0)
</code></pre>
|
[
{
"answer_id": 253277,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>It's really quite simple. The theme author is using a constant that you can put in <code>wp-config.php</code>, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning</p>\n\n<p><a href=\"https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions</a></p>\n\n<blockquote>\n <h3>Override of default file permissions</h3>\n \n <p>The FS_CHMOD_DIR and\n FS_CHMOD_FILE define statements allow override of default file\n permissions. These two variables were developed in response to the\n problem of the core update function failing with hosts running under\n suexec. If a host uses restrictive file permissions (e.g. 400) for all\n user files, and refuses to access files which have group or world\n permissions set, these definitions could solve the problem. Note that\n the '0755' is an octal value. Octal values must be prefixed with a 0\n and are not delineated with single quotes ('). See Also: Changing File\n Permissions</p>\n</blockquote>\n\n<h2>FAQ</h2>\n\n<h3>So Who's to Blame?</h3>\n\n<p>The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.</p>\n\n<p>The check is an easy thing to do:</p>\n\n<pre><code>$chmod_dir = ( 0755 & ~ umask() );\nif ( defined( 'FS_CHMOD_DIR' ) ) {\n $chmod_dir = FS_CHMOD_DIR;\n}\n</code></pre>\n\n<p>You use a variable, give it a default variable, then assign the constant to it if it exists.</p>\n\n<h3>What about this file PHP extension?</h3>\n\n<p>It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )</p>\n\n<h3>Is all of this above board?</h3>\n\n<p>Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.</p>\n\n<p>I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder )</p>\n"
},
{
"answer_id": 406106,
"author": "r_D",
"author_id": 222544,
"author_profile": "https://wordpress.stackexchange.com/users/222544",
"pm_score": 0,
"selected": false,
"text": "<p>I faced the same issue, it was due to the permissions of <code>/var/www/html/*</code> files and folders.</p>\n<p>It was owned by root, changed the owner to <code>www-data:www-data</code></p>\n<pre><code>cd /var/www/html\nsudo chown -R www-data:www-data *\n</code></pre>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253290",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110929/"
] |
I have this php file on the root directory, and i seen this example for inserting post from external php file
but for some reason it doesn't work for me, `wp_insert_post()` always returns `0`
So whats the problem ? and how i can fix it?
I'm trying to build a Cron Job file to insert new posts from XML file In the end
Thank you!
CronJob.php:
```
<?php
require_once './wp-load.php';
$new_post = array(
'post_title' => 'My New Post',
'post_content' => 'Lorem ipsum dolor sit amet...',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => '3',
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
var_dump($post_id); die; // Return int(0)
```
|
It's really quite simple. The theme author is using a constant that you can put in `wp-config.php`, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning
<https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions>
>
> ### Override of default file permissions
>
>
> The FS\_CHMOD\_DIR and
> FS\_CHMOD\_FILE define statements allow override of default file
> permissions. These two variables were developed in response to the
> problem of the core update function failing with hosts running under
> suexec. If a host uses restrictive file permissions (e.g. 400) for all
> user files, and refuses to access files which have group or world
> permissions set, these definitions could solve the problem. Note that
> the '0755' is an octal value. Octal values must be prefixed with a 0
> and are not delineated with single quotes ('). See Also: Changing File
> Permissions
>
>
>
FAQ
---
### So Who's to Blame?
The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.
The check is an easy thing to do:
```
$chmod_dir = ( 0755 & ~ umask() );
if ( defined( 'FS_CHMOD_DIR' ) ) {
$chmod_dir = FS_CHMOD_DIR;
}
```
You use a variable, give it a default variable, then assign the constant to it if it exists.
### What about this file PHP extension?
It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )
### Is all of this above board?
Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.
I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder )
|
253,315 |
<p>Looks like WordPress unnecessarily fire WP CRON on every page load. I'm thinking, instead of having it run on every visit, why not just schedule it to run every 5 minutes via server? I could simply trigger wp-cron.php every five minutes and achieve desired result?</p>
<p>Is there any downside to this? </p>
|
[
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER variables aren't set. People overcome this limitation by using a curl request to wp-cron.php instead. </p>\n\n<p>Secondly, Because WP itself isn't loaded with wp-cron.php; if you use a SMTP mailer plugin then this won't be loaded when calling wp-cron. Again, using a curl call overrides this problem. Curl seems to be the most frequently used method. </p>\n\n<p>However; I prefer to use wp-cli after setting mail settings in postfix and (for nginx) php-fpm config correctly and setting a crontab such as </p>\n\n<pre><code>*/5 * * * * wp cron event list --skip-plugins --skip-themes --path=\"/var/www/vhosts/example.com/httpdocs/wp\" --fields=hook,next_run_relative --format=csv | awk -F, '$2==\"now\" {print $1}' | xargs -r wp --path=\"/var/www/vhosts/example.com/httpdocs/wp\" cron event run $1\n</code></pre>\n\n<p>(List all crons with specific fields in csv format - hook being the name of the cron, next run relative is the time. Strip out ones showing 'now' as next run (ones due now) using AWK, pass that list to xargs to call <code>wp cron event run $HOOK</code> on each cron. )\nUsing wp-cli loads WordPress correctly (I choose to skip plugins when listing the crons, as code erros and php warnings will screw up the scripted output; but not to skip them when running the cron with xargs, as the cron may need the plugins being loaded)</p>\n\n<p>Hope this gives you some pointers in what to look out for. </p>\n"
},
{
"answer_id": 253331,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": false,
"text": "<p>There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.</p>\n\n<p>According to <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"noreferrer\">Official WordPress Plugin Development Document</a>:</p>\n\n<blockquote>\n <p>WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).</p>\n</blockquote>\n\n<p>To do this, you need to first disable the default cron behaviour in <code>wp-config.php</code>:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n\n<p>Then, schedule <code>wp-cron.php</code> from your server. For Linux, that means:</p>\n\n<pre><code>crontab -e\n</code></pre>\n\n<p>However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use <code>wget</code>:</p>\n\n<pre><code>*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron\n</code></pre>\n\n<p>WordPress loads all the required core files, Plugins etc. in <code>wp-cron.php</code> with the following CODE:</p>\n\n<pre><code>if ( !defined('ABSPATH') ) {\n /** Set up WordPress environment */\n require_once( dirname( __FILE__ ) . '/wp-load.php' );\n}\n</code></pre>\n\n<p>So don't worry about WordPress not loading important features.</p>\n"
},
{
"answer_id": 349342,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": -1,
"selected": false,
"text": "<p>There are many reasons not to disable the wp-cron. In fact, it's nearly impossible to find a use case to do this. It doesn't slow your site down, and it is used for things you may not be aware of.</p>\n\n<p>Many plugins use the WP-Cron to schedule things. They may become confused if you turn off the scheduler. </p>\n\n<p>There is a proliferation of tutorials on this subject because it is confusing, and because it doesn't do much to your site when you disable it. What it will do, is cause a headache to the dev who has to fix the mysterious problem it creates in six months.</p>\n\n<p>Also, the WP Heartbeat fires every 15 seconds in the admin area, solving this issue for 99% of the people who think they have it.</p>\n"
},
{
"answer_id": 358021,
"author": "Radoslav Stefanov",
"author_id": 134464,
"author_profile": "https://wordpress.stackexchange.com/users/134464",
"pm_score": 1,
"selected": false,
"text": "<p>I am yet to find a real downside to offloading wp-cron to external service. Being doing this for many years now.</p>\n\n<p>Especially in todays world where you can run applications as microservices. </p>\n\n<p>I use separate Docker containers for each WordPress component - php, web, db, crontab, redis and so on). Having crontab as separate container, calling wp-cron via http using local network, running only when I need it to.</p>\n\n<p>This reduces stress on backend nodes and improves security by having smaller attack surface.</p>\n\n<p>If the developer can't figure out how to do stuff without having to call wp-cron on every page load, heck, this just speaks for inexperience on his behalf. \"Leaving it alone\", because you don't understand how things work is not a good reason to keep it.</p>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253315",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21100/"
] |
Looks like WordPress unnecessarily fire WP CRON on every page load. I'm thinking, instead of having it run on every visit, why not just schedule it to run every 5 minutes via server? I could simply trigger wp-cron.php every five minutes and achieve desired result?
Is there any downside to this?
|
There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features.
|
253,316 |
<p>I just reinstalled Wordpress to fix another problem. I followed careful instructions about backing up my database but now I get error 1062 from mySQL when I try to reinstall the database. This is because a duplicate database seems to have been created, stopping me uploading my saved version.</p>
<p>How can I delete/override the duplicate database? </p>
<p>Thanks</p>
|
[
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER variables aren't set. People overcome this limitation by using a curl request to wp-cron.php instead. </p>\n\n<p>Secondly, Because WP itself isn't loaded with wp-cron.php; if you use a SMTP mailer plugin then this won't be loaded when calling wp-cron. Again, using a curl call overrides this problem. Curl seems to be the most frequently used method. </p>\n\n<p>However; I prefer to use wp-cli after setting mail settings in postfix and (for nginx) php-fpm config correctly and setting a crontab such as </p>\n\n<pre><code>*/5 * * * * wp cron event list --skip-plugins --skip-themes --path=\"/var/www/vhosts/example.com/httpdocs/wp\" --fields=hook,next_run_relative --format=csv | awk -F, '$2==\"now\" {print $1}' | xargs -r wp --path=\"/var/www/vhosts/example.com/httpdocs/wp\" cron event run $1\n</code></pre>\n\n<p>(List all crons with specific fields in csv format - hook being the name of the cron, next run relative is the time. Strip out ones showing 'now' as next run (ones due now) using AWK, pass that list to xargs to call <code>wp cron event run $HOOK</code> on each cron. )\nUsing wp-cli loads WordPress correctly (I choose to skip plugins when listing the crons, as code erros and php warnings will screw up the scripted output; but not to skip them when running the cron with xargs, as the cron may need the plugins being loaded)</p>\n\n<p>Hope this gives you some pointers in what to look out for. </p>\n"
},
{
"answer_id": 253331,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": false,
"text": "<p>There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.</p>\n\n<p>According to <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"noreferrer\">Official WordPress Plugin Development Document</a>:</p>\n\n<blockquote>\n <p>WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).</p>\n</blockquote>\n\n<p>To do this, you need to first disable the default cron behaviour in <code>wp-config.php</code>:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n\n<p>Then, schedule <code>wp-cron.php</code> from your server. For Linux, that means:</p>\n\n<pre><code>crontab -e\n</code></pre>\n\n<p>However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use <code>wget</code>:</p>\n\n<pre><code>*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron\n</code></pre>\n\n<p>WordPress loads all the required core files, Plugins etc. in <code>wp-cron.php</code> with the following CODE:</p>\n\n<pre><code>if ( !defined('ABSPATH') ) {\n /** Set up WordPress environment */\n require_once( dirname( __FILE__ ) . '/wp-load.php' );\n}\n</code></pre>\n\n<p>So don't worry about WordPress not loading important features.</p>\n"
},
{
"answer_id": 349342,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": -1,
"selected": false,
"text": "<p>There are many reasons not to disable the wp-cron. In fact, it's nearly impossible to find a use case to do this. It doesn't slow your site down, and it is used for things you may not be aware of.</p>\n\n<p>Many plugins use the WP-Cron to schedule things. They may become confused if you turn off the scheduler. </p>\n\n<p>There is a proliferation of tutorials on this subject because it is confusing, and because it doesn't do much to your site when you disable it. What it will do, is cause a headache to the dev who has to fix the mysterious problem it creates in six months.</p>\n\n<p>Also, the WP Heartbeat fires every 15 seconds in the admin area, solving this issue for 99% of the people who think they have it.</p>\n"
},
{
"answer_id": 358021,
"author": "Radoslav Stefanov",
"author_id": 134464,
"author_profile": "https://wordpress.stackexchange.com/users/134464",
"pm_score": 1,
"selected": false,
"text": "<p>I am yet to find a real downside to offloading wp-cron to external service. Being doing this for many years now.</p>\n\n<p>Especially in todays world where you can run applications as microservices. </p>\n\n<p>I use separate Docker containers for each WordPress component - php, web, db, crontab, redis and so on). Having crontab as separate container, calling wp-cron via http using local network, running only when I need it to.</p>\n\n<p>This reduces stress on backend nodes and improves security by having smaller attack surface.</p>\n\n<p>If the developer can't figure out how to do stuff without having to call wp-cron on every page load, heck, this just speaks for inexperience on his behalf. \"Leaving it alone\", because you don't understand how things work is not a good reason to keep it.</p>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253316",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110850/"
] |
I just reinstalled Wordpress to fix another problem. I followed careful instructions about backing up my database but now I get error 1062 from mySQL when I try to reinstall the database. This is because a duplicate database seems to have been created, stopping me uploading my saved version.
How can I delete/override the duplicate database?
Thanks
|
There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features.
|
253,333 |
<p>I have a search page that when you enter a blank query, it shows posts and pages together. This isn't an issue, it's fine. However I'd like to remove some details like the date from the pages as it doesn't make much sense.</p>
<p>I'm using the is_page function but that doesn't seem to work and I have no idea why, I'm including all of the necessary information (or so I thought).</p>
<pre><code><?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>">
<?php if ( is_page() ) : ?>
<?php the_title(); ?>
<?php else : ?>
<?php the_title(); ?>
<?php the_time("jS F Y"); ?>
<?php foreach ( get_the_category() as $the_category ) : ?>
<?php echo $the_category->cat_name; ?>
<?php endforeach; ?>
<?php endif; ?>
</article>
<?php endwhile; ?>
</code></pre>
<p>The <a href="https://developer.wordpress.org/reference/functions/is_page/" rel="nofollow noreferrer">is_page</a> function in the WP Codex.</p>
|
[
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER variables aren't set. People overcome this limitation by using a curl request to wp-cron.php instead. </p>\n\n<p>Secondly, Because WP itself isn't loaded with wp-cron.php; if you use a SMTP mailer plugin then this won't be loaded when calling wp-cron. Again, using a curl call overrides this problem. Curl seems to be the most frequently used method. </p>\n\n<p>However; I prefer to use wp-cli after setting mail settings in postfix and (for nginx) php-fpm config correctly and setting a crontab such as </p>\n\n<pre><code>*/5 * * * * wp cron event list --skip-plugins --skip-themes --path=\"/var/www/vhosts/example.com/httpdocs/wp\" --fields=hook,next_run_relative --format=csv | awk -F, '$2==\"now\" {print $1}' | xargs -r wp --path=\"/var/www/vhosts/example.com/httpdocs/wp\" cron event run $1\n</code></pre>\n\n<p>(List all crons with specific fields in csv format - hook being the name of the cron, next run relative is the time. Strip out ones showing 'now' as next run (ones due now) using AWK, pass that list to xargs to call <code>wp cron event run $HOOK</code> on each cron. )\nUsing wp-cli loads WordPress correctly (I choose to skip plugins when listing the crons, as code erros and php warnings will screw up the scripted output; but not to skip them when running the cron with xargs, as the cron may need the plugins being loaded)</p>\n\n<p>Hope this gives you some pointers in what to look out for. </p>\n"
},
{
"answer_id": 253331,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": false,
"text": "<p>There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.</p>\n\n<p>According to <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"noreferrer\">Official WordPress Plugin Development Document</a>:</p>\n\n<blockquote>\n <p>WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).</p>\n</blockquote>\n\n<p>To do this, you need to first disable the default cron behaviour in <code>wp-config.php</code>:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n\n<p>Then, schedule <code>wp-cron.php</code> from your server. For Linux, that means:</p>\n\n<pre><code>crontab -e\n</code></pre>\n\n<p>However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use <code>wget</code>:</p>\n\n<pre><code>*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron\n</code></pre>\n\n<p>WordPress loads all the required core files, Plugins etc. in <code>wp-cron.php</code> with the following CODE:</p>\n\n<pre><code>if ( !defined('ABSPATH') ) {\n /** Set up WordPress environment */\n require_once( dirname( __FILE__ ) . '/wp-load.php' );\n}\n</code></pre>\n\n<p>So don't worry about WordPress not loading important features.</p>\n"
},
{
"answer_id": 349342,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": -1,
"selected": false,
"text": "<p>There are many reasons not to disable the wp-cron. In fact, it's nearly impossible to find a use case to do this. It doesn't slow your site down, and it is used for things you may not be aware of.</p>\n\n<p>Many plugins use the WP-Cron to schedule things. They may become confused if you turn off the scheduler. </p>\n\n<p>There is a proliferation of tutorials on this subject because it is confusing, and because it doesn't do much to your site when you disable it. What it will do, is cause a headache to the dev who has to fix the mysterious problem it creates in six months.</p>\n\n<p>Also, the WP Heartbeat fires every 15 seconds in the admin area, solving this issue for 99% of the people who think they have it.</p>\n"
},
{
"answer_id": 358021,
"author": "Radoslav Stefanov",
"author_id": 134464,
"author_profile": "https://wordpress.stackexchange.com/users/134464",
"pm_score": 1,
"selected": false,
"text": "<p>I am yet to find a real downside to offloading wp-cron to external service. Being doing this for many years now.</p>\n\n<p>Especially in todays world where you can run applications as microservices. </p>\n\n<p>I use separate Docker containers for each WordPress component - php, web, db, crontab, redis and so on). Having crontab as separate container, calling wp-cron via http using local network, running only when I need it to.</p>\n\n<p>This reduces stress on backend nodes and improves security by having smaller attack surface.</p>\n\n<p>If the developer can't figure out how to do stuff without having to call wp-cron on every page load, heck, this just speaks for inexperience on his behalf. \"Leaving it alone\", because you don't understand how things work is not a good reason to keep it.</p>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253333",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
I have a search page that when you enter a blank query, it shows posts and pages together. This isn't an issue, it's fine. However I'd like to remove some details like the date from the pages as it doesn't make much sense.
I'm using the is\_page function but that doesn't seem to work and I have no idea why, I'm including all of the necessary information (or so I thought).
```
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>">
<?php if ( is_page() ) : ?>
<?php the_title(); ?>
<?php else : ?>
<?php the_title(); ?>
<?php the_time("jS F Y"); ?>
<?php foreach ( get_the_category() as $the_category ) : ?>
<?php echo $the_category->cat_name; ?>
<?php endforeach; ?>
<?php endif; ?>
</article>
<?php endwhile; ?>
```
The [is\_page](https://developer.wordpress.org/reference/functions/is_page/) function in the WP Codex.
|
There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features.
|
253,344 |
<p>I dont want to show image in my read_more function in homepage. read_more shows first 25 strings of my content. when I add image in the content it shows with the string inline. I don't want the image. Anyone know how to do it? here is my code below..</p>
<pre><code><div id="leadnewsbox" class="col-md-5 col-sm-4 col-xs-12">
<?php
$breakingcat = get_the_category_by_id($btimes['breaking-news-category']);
$breakingnews = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 1,
'category_name' => $breakingcat
));
while($breakingnews->have_posts()) : $breakingnews->the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('post-image'); ?></a>
<div class="leadnewsboxtitle">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php read_more(25); ?>...</p>
</div>
<?php endwhile; ?>
</code></pre>
<p></p>
<pre><code>// read_more function
function read_more($limit){
$content = explode(' ', get_the_content());
$less_content = array_slice($content, 0 , $limit);
echo implode (' ', $less_content);
}
</code></pre>
|
[
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER variables aren't set. People overcome this limitation by using a curl request to wp-cron.php instead. </p>\n\n<p>Secondly, Because WP itself isn't loaded with wp-cron.php; if you use a SMTP mailer plugin then this won't be loaded when calling wp-cron. Again, using a curl call overrides this problem. Curl seems to be the most frequently used method. </p>\n\n<p>However; I prefer to use wp-cli after setting mail settings in postfix and (for nginx) php-fpm config correctly and setting a crontab such as </p>\n\n<pre><code>*/5 * * * * wp cron event list --skip-plugins --skip-themes --path=\"/var/www/vhosts/example.com/httpdocs/wp\" --fields=hook,next_run_relative --format=csv | awk -F, '$2==\"now\" {print $1}' | xargs -r wp --path=\"/var/www/vhosts/example.com/httpdocs/wp\" cron event run $1\n</code></pre>\n\n<p>(List all crons with specific fields in csv format - hook being the name of the cron, next run relative is the time. Strip out ones showing 'now' as next run (ones due now) using AWK, pass that list to xargs to call <code>wp cron event run $HOOK</code> on each cron. )\nUsing wp-cli loads WordPress correctly (I choose to skip plugins when listing the crons, as code erros and php warnings will screw up the scripted output; but not to skip them when running the cron with xargs, as the cron may need the plugins being loaded)</p>\n\n<p>Hope this gives you some pointers in what to look out for. </p>\n"
},
{
"answer_id": 253331,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": false,
"text": "<p>There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.</p>\n\n<p>According to <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"noreferrer\">Official WordPress Plugin Development Document</a>:</p>\n\n<blockquote>\n <p>WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).</p>\n</blockquote>\n\n<p>To do this, you need to first disable the default cron behaviour in <code>wp-config.php</code>:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n\n<p>Then, schedule <code>wp-cron.php</code> from your server. For Linux, that means:</p>\n\n<pre><code>crontab -e\n</code></pre>\n\n<p>However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use <code>wget</code>:</p>\n\n<pre><code>*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron\n</code></pre>\n\n<p>WordPress loads all the required core files, Plugins etc. in <code>wp-cron.php</code> with the following CODE:</p>\n\n<pre><code>if ( !defined('ABSPATH') ) {\n /** Set up WordPress environment */\n require_once( dirname( __FILE__ ) . '/wp-load.php' );\n}\n</code></pre>\n\n<p>So don't worry about WordPress not loading important features.</p>\n"
},
{
"answer_id": 349342,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": -1,
"selected": false,
"text": "<p>There are many reasons not to disable the wp-cron. In fact, it's nearly impossible to find a use case to do this. It doesn't slow your site down, and it is used for things you may not be aware of.</p>\n\n<p>Many plugins use the WP-Cron to schedule things. They may become confused if you turn off the scheduler. </p>\n\n<p>There is a proliferation of tutorials on this subject because it is confusing, and because it doesn't do much to your site when you disable it. What it will do, is cause a headache to the dev who has to fix the mysterious problem it creates in six months.</p>\n\n<p>Also, the WP Heartbeat fires every 15 seconds in the admin area, solving this issue for 99% of the people who think they have it.</p>\n"
},
{
"answer_id": 358021,
"author": "Radoslav Stefanov",
"author_id": 134464,
"author_profile": "https://wordpress.stackexchange.com/users/134464",
"pm_score": 1,
"selected": false,
"text": "<p>I am yet to find a real downside to offloading wp-cron to external service. Being doing this for many years now.</p>\n\n<p>Especially in todays world where you can run applications as microservices. </p>\n\n<p>I use separate Docker containers for each WordPress component - php, web, db, crontab, redis and so on). Having crontab as separate container, calling wp-cron via http using local network, running only when I need it to.</p>\n\n<p>This reduces stress on backend nodes and improves security by having smaller attack surface.</p>\n\n<p>If the developer can't figure out how to do stuff without having to call wp-cron on every page load, heck, this just speaks for inexperience on his behalf. \"Leaving it alone\", because you don't understand how things work is not a good reason to keep it.</p>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253344",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111404/"
] |
I dont want to show image in my read\_more function in homepage. read\_more shows first 25 strings of my content. when I add image in the content it shows with the string inline. I don't want the image. Anyone know how to do it? here is my code below..
```
<div id="leadnewsbox" class="col-md-5 col-sm-4 col-xs-12">
<?php
$breakingcat = get_the_category_by_id($btimes['breaking-news-category']);
$breakingnews = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 1,
'category_name' => $breakingcat
));
while($breakingnews->have_posts()) : $breakingnews->the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('post-image'); ?></a>
<div class="leadnewsboxtitle">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php read_more(25); ?>...</p>
</div>
<?php endwhile; ?>
```
```
// read_more function
function read_more($limit){
$content = explode(' ', get_the_content());
$less_content = array_slice($content, 0 , $limit);
echo implode (' ', $less_content);
}
```
|
There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features.
|
253,351 |
<p>Hi I am new to Wordpress development and I have learned a lot already but I do not understand why the text and content in the pages and posts does not keep the format that the user sets in the back-end editor for posts or pages. And everything looks like a mess, formatting goes wild and it does not resemble the editor version at all. What am I missing in my code? I don't understand what is wrong, is it my css rules? </p>
<p>A funny thing is that when I change to another theme, the formatting does remain in place. And it seems to work with any theme available in the wordpress themes section.</p>
<p>Please help. </p>
|
[
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER variables aren't set. People overcome this limitation by using a curl request to wp-cron.php instead. </p>\n\n<p>Secondly, Because WP itself isn't loaded with wp-cron.php; if you use a SMTP mailer plugin then this won't be loaded when calling wp-cron. Again, using a curl call overrides this problem. Curl seems to be the most frequently used method. </p>\n\n<p>However; I prefer to use wp-cli after setting mail settings in postfix and (for nginx) php-fpm config correctly and setting a crontab such as </p>\n\n<pre><code>*/5 * * * * wp cron event list --skip-plugins --skip-themes --path=\"/var/www/vhosts/example.com/httpdocs/wp\" --fields=hook,next_run_relative --format=csv | awk -F, '$2==\"now\" {print $1}' | xargs -r wp --path=\"/var/www/vhosts/example.com/httpdocs/wp\" cron event run $1\n</code></pre>\n\n<p>(List all crons with specific fields in csv format - hook being the name of the cron, next run relative is the time. Strip out ones showing 'now' as next run (ones due now) using AWK, pass that list to xargs to call <code>wp cron event run $HOOK</code> on each cron. )\nUsing wp-cli loads WordPress correctly (I choose to skip plugins when listing the crons, as code erros and php warnings will screw up the scripted output; but not to skip them when running the cron with xargs, as the cron may need the plugins being loaded)</p>\n\n<p>Hope this gives you some pointers in what to look out for. </p>\n"
},
{
"answer_id": 253331,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": false,
"text": "<p>There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.</p>\n\n<p>According to <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"noreferrer\">Official WordPress Plugin Development Document</a>:</p>\n\n<blockquote>\n <p>WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).</p>\n</blockquote>\n\n<p>To do this, you need to first disable the default cron behaviour in <code>wp-config.php</code>:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n\n<p>Then, schedule <code>wp-cron.php</code> from your server. For Linux, that means:</p>\n\n<pre><code>crontab -e\n</code></pre>\n\n<p>However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use <code>wget</code>:</p>\n\n<pre><code>*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron\n</code></pre>\n\n<p>WordPress loads all the required core files, Plugins etc. in <code>wp-cron.php</code> with the following CODE:</p>\n\n<pre><code>if ( !defined('ABSPATH') ) {\n /** Set up WordPress environment */\n require_once( dirname( __FILE__ ) . '/wp-load.php' );\n}\n</code></pre>\n\n<p>So don't worry about WordPress not loading important features.</p>\n"
},
{
"answer_id": 349342,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": -1,
"selected": false,
"text": "<p>There are many reasons not to disable the wp-cron. In fact, it's nearly impossible to find a use case to do this. It doesn't slow your site down, and it is used for things you may not be aware of.</p>\n\n<p>Many plugins use the WP-Cron to schedule things. They may become confused if you turn off the scheduler. </p>\n\n<p>There is a proliferation of tutorials on this subject because it is confusing, and because it doesn't do much to your site when you disable it. What it will do, is cause a headache to the dev who has to fix the mysterious problem it creates in six months.</p>\n\n<p>Also, the WP Heartbeat fires every 15 seconds in the admin area, solving this issue for 99% of the people who think they have it.</p>\n"
},
{
"answer_id": 358021,
"author": "Radoslav Stefanov",
"author_id": 134464,
"author_profile": "https://wordpress.stackexchange.com/users/134464",
"pm_score": 1,
"selected": false,
"text": "<p>I am yet to find a real downside to offloading wp-cron to external service. Being doing this for many years now.</p>\n\n<p>Especially in todays world where you can run applications as microservices. </p>\n\n<p>I use separate Docker containers for each WordPress component - php, web, db, crontab, redis and so on). Having crontab as separate container, calling wp-cron via http using local network, running only when I need it to.</p>\n\n<p>This reduces stress on backend nodes and improves security by having smaller attack surface.</p>\n\n<p>If the developer can't figure out how to do stuff without having to call wp-cron on every page load, heck, this just speaks for inexperience on his behalf. \"Leaving it alone\", because you don't understand how things work is not a good reason to keep it.</p>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253351",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106353/"
] |
Hi I am new to Wordpress development and I have learned a lot already but I do not understand why the text and content in the pages and posts does not keep the format that the user sets in the back-end editor for posts or pages. And everything looks like a mess, formatting goes wild and it does not resemble the editor version at all. What am I missing in my code? I don't understand what is wrong, is it my css rules?
A funny thing is that when I change to another theme, the formatting does remain in place. And it seems to work with any theme available in the wordpress themes section.
Please help.
|
There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features.
|
253,353 |
<p>I'm looking for help on how to add specific menu on a specific page or pages with no plugin.</p>
<p>I know how to add and register a new menu like this:</p>
<pre><code>//* Register third navigation menu position
function register_additional_menu() {
register_nav_menu( 'third-menu' ,__( 'Third Navigation Menu' ));
}
add_action( 'init', 'register_additional_menu' );
add_action( 'genesis_before_content', 'add_third_nav_genesis' );
function add_third_nav_genesis() {
echo'<div class="osastot-valikko">';
wp_nav_menu( array( 'theme_location' => 'third-menu', 'container_class' => 'genesis-nav-menu js-superfish sf-js-enabled sf-arrows' ) );
echo'</div>';
}
</code></pre>
<p>I would like to have a navigation menu named "Extra Menu" displayed only on three pages (post=6, post=7, post=8). What should I write in my function.php</p>
<p>Thanks!</p>
|
[
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER variables aren't set. People overcome this limitation by using a curl request to wp-cron.php instead. </p>\n\n<p>Secondly, Because WP itself isn't loaded with wp-cron.php; if you use a SMTP mailer plugin then this won't be loaded when calling wp-cron. Again, using a curl call overrides this problem. Curl seems to be the most frequently used method. </p>\n\n<p>However; I prefer to use wp-cli after setting mail settings in postfix and (for nginx) php-fpm config correctly and setting a crontab such as </p>\n\n<pre><code>*/5 * * * * wp cron event list --skip-plugins --skip-themes --path=\"/var/www/vhosts/example.com/httpdocs/wp\" --fields=hook,next_run_relative --format=csv | awk -F, '$2==\"now\" {print $1}' | xargs -r wp --path=\"/var/www/vhosts/example.com/httpdocs/wp\" cron event run $1\n</code></pre>\n\n<p>(List all crons with specific fields in csv format - hook being the name of the cron, next run relative is the time. Strip out ones showing 'now' as next run (ones due now) using AWK, pass that list to xargs to call <code>wp cron event run $HOOK</code> on each cron. )\nUsing wp-cli loads WordPress correctly (I choose to skip plugins when listing the crons, as code erros and php warnings will screw up the scripted output; but not to skip them when running the cron with xargs, as the cron may need the plugins being loaded)</p>\n\n<p>Hope this gives you some pointers in what to look out for. </p>\n"
},
{
"answer_id": 253331,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": false,
"text": "<p>There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.</p>\n\n<p>According to <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"noreferrer\">Official WordPress Plugin Development Document</a>:</p>\n\n<blockquote>\n <p>WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).</p>\n</blockquote>\n\n<p>To do this, you need to first disable the default cron behaviour in <code>wp-config.php</code>:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n\n<p>Then, schedule <code>wp-cron.php</code> from your server. For Linux, that means:</p>\n\n<pre><code>crontab -e\n</code></pre>\n\n<p>However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use <code>wget</code>:</p>\n\n<pre><code>*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron\n</code></pre>\n\n<p>WordPress loads all the required core files, Plugins etc. in <code>wp-cron.php</code> with the following CODE:</p>\n\n<pre><code>if ( !defined('ABSPATH') ) {\n /** Set up WordPress environment */\n require_once( dirname( __FILE__ ) . '/wp-load.php' );\n}\n</code></pre>\n\n<p>So don't worry about WordPress not loading important features.</p>\n"
},
{
"answer_id": 349342,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": -1,
"selected": false,
"text": "<p>There are many reasons not to disable the wp-cron. In fact, it's nearly impossible to find a use case to do this. It doesn't slow your site down, and it is used for things you may not be aware of.</p>\n\n<p>Many plugins use the WP-Cron to schedule things. They may become confused if you turn off the scheduler. </p>\n\n<p>There is a proliferation of tutorials on this subject because it is confusing, and because it doesn't do much to your site when you disable it. What it will do, is cause a headache to the dev who has to fix the mysterious problem it creates in six months.</p>\n\n<p>Also, the WP Heartbeat fires every 15 seconds in the admin area, solving this issue for 99% of the people who think they have it.</p>\n"
},
{
"answer_id": 358021,
"author": "Radoslav Stefanov",
"author_id": 134464,
"author_profile": "https://wordpress.stackexchange.com/users/134464",
"pm_score": 1,
"selected": false,
"text": "<p>I am yet to find a real downside to offloading wp-cron to external service. Being doing this for many years now.</p>\n\n<p>Especially in todays world where you can run applications as microservices. </p>\n\n<p>I use separate Docker containers for each WordPress component - php, web, db, crontab, redis and so on). Having crontab as separate container, calling wp-cron via http using local network, running only when I need it to.</p>\n\n<p>This reduces stress on backend nodes and improves security by having smaller attack surface.</p>\n\n<p>If the developer can't figure out how to do stuff without having to call wp-cron on every page load, heck, this just speaks for inexperience on his behalf. \"Leaving it alone\", because you don't understand how things work is not a good reason to keep it.</p>\n"
}
] |
2017/01/20
|
[
"https://wordpress.stackexchange.com/questions/253353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111269/"
] |
I'm looking for help on how to add specific menu on a specific page or pages with no plugin.
I know how to add and register a new menu like this:
```
//* Register third navigation menu position
function register_additional_menu() {
register_nav_menu( 'third-menu' ,__( 'Third Navigation Menu' ));
}
add_action( 'init', 'register_additional_menu' );
add_action( 'genesis_before_content', 'add_third_nav_genesis' );
function add_third_nav_genesis() {
echo'<div class="osastot-valikko">';
wp_nav_menu( array( 'theme_location' => 'third-menu', 'container_class' => 'genesis-nav-menu js-superfish sf-js-enabled sf-arrows' ) );
echo'</div>';
}
```
I would like to have a navigation menu named "Extra Menu" displayed only on three pages (post=6, post=7, post=8). What should I write in my function.php
Thanks!
|
There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features.
|
253,385 |
<p>Goal: convert Facebook url itself (without full code snippet) into Facebook post on website front-end</p>
<p>Problem: The experimental o2 / p2 / breathe theme, by default, converts a full Facebook code snippet in the editor to a full Facebook post on the front-end. Example snippet:</p>
<pre><code><div class="fb-post" data-href="https://www.facebook.com/WordPresscom/posts/10154113693553980" max-width="90%">
</code></pre>
<p>I would like to instead just be able to post ONLY the url into the editor and have the url wrapped with <code><div class="fb-post" data-href=" ... " max-width="90%"></code> in the source-code.</p>
<p>I assume I would need to do this through functions.php?</p>
|
[
{
"answer_id": 253390,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>You need to use the php <code>preg_replace</code>function in order to transform your url into an snippet.</p>\n<p>Please keep in mind:</p>\n<ul>\n<li>The URLs must be started with <code>http://facebook.com/</code> or <code>https://facebook.com/</code> for the function to work.</li>\n<li>If you someday try to add a link without turning into an snippet, you will face problems since this function will turn any facebook link into an snippet.</li>\n<li>I haven't tested the code myself, you can check <a href=\"https://www.php.net/manual/en/function.preg-replace.php\" rel=\"nofollow noreferrer\">this</a> link and modify the rules to achieve the best results.</li>\n</ul>\n<p>Add the following code to you <code>function.php</code> file:</p>\n<pre><code> add_filter( 'the_content', 'the_facebook_filter', 20 );\n function the_facebook_filter( $content ) {\n $fb_links = wp_extract_urls( $content );\n $string = preg_replace('#http://facebook.com/(.*?)#i', '<div class="fb-post" data-href="\\1" max-width="90%"></div>', $fb_links[0]);\n $string = preg_replace('#https://facebook.com/(.*?)#i', '<div class="fb-post" data-href="\\1" max-width="90%"></div>', $fb_links[0]);\n return $string;\n}\n</code></pre>\n"
},
{
"answer_id": 253413,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Note that Facebook is a registered <em>oEmbed</em> provider in the WordPress core.</p>\n\n<p>You could e.g. use the <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-oembed.php#L350\" rel=\"nofollow noreferrer\"><code>pre_oembed_result</code></a> filter, before the HTTP request is made, to cancel it and override it to your needs.</p>\n\n<p>Here's an example for Facebook posts:</p>\n\n<pre><code>add_filter( 'pre_oembed_result', function ( $result, $url, $args )\n{ \n // override the HTML result for Facebook posts, that will be saved into postmeta table\n if( preg_match( '#https?://www\\.facebook\\.com/.*/posts/.*#i', $url ) )\n $result = sprintf( \n '<div class=\"fb-post\" data-href=\"%s\">%s</div>',\n esc_url( $url ), \n esc_url( $url ) \n );\n\n return $result;\n\n}, 10, 3 );\n</code></pre>\n\n<p>When you paste a Facebook post url, into the post content editor, it will also show the modified oEmbed result, with our snippet.</p>\n\n<p>The oEmbed results are <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-embed.php#L210\" rel=\"nofollow noreferrer\">cached</a> by default in the postmeta table, for <code>DAY_IN_SECONDS</code> (24 hours).</p>\n\n<p>We can play with the <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-embed.php#L210\" rel=\"nofollow noreferrer\"><code>oembed_ttl</code></a> filter, like <a href=\"https://wordpress.stackexchange.com/a/203558/26350\">here</a>, but in the meanwhile we can also filter the cached output with the <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-embed.php#L239\" rel=\"nofollow noreferrer\"><code>embed_oembed_html</code></a> filter.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>add_filter( 'embed_oembed_html', function( $cache, $url, $attr, $post_id )\n{\n // override the cached HTML result for Facebook posts\n if( preg_match( '#https?://www\\.facebook\\.com/.*/posts/.*#i', $url ) )\n $cache = sprintf( \n '<div class=\"fb-post\" data-href=\"%s\">%s</div>',\n esc_url( $url ), \n esc_url( $url ) \n );\n\n return $cache;\n\n}, 10, 4 );\n</code></pre>\n"
}
] |
2017/01/21
|
[
"https://wordpress.stackexchange.com/questions/253385",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1697/"
] |
Goal: convert Facebook url itself (without full code snippet) into Facebook post on website front-end
Problem: The experimental o2 / p2 / breathe theme, by default, converts a full Facebook code snippet in the editor to a full Facebook post on the front-end. Example snippet:
```
<div class="fb-post" data-href="https://www.facebook.com/WordPresscom/posts/10154113693553980" max-width="90%">
```
I would like to instead just be able to post ONLY the url into the editor and have the url wrapped with `<div class="fb-post" data-href=" ... " max-width="90%">` in the source-code.
I assume I would need to do this through functions.php?
|
Note that Facebook is a registered *oEmbed* provider in the WordPress core.
You could e.g. use the [`pre_oembed_result`](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-oembed.php#L350) filter, before the HTTP request is made, to cancel it and override it to your needs.
Here's an example for Facebook posts:
```
add_filter( 'pre_oembed_result', function ( $result, $url, $args )
{
// override the HTML result for Facebook posts, that will be saved into postmeta table
if( preg_match( '#https?://www\.facebook\.com/.*/posts/.*#i', $url ) )
$result = sprintf(
'<div class="fb-post" data-href="%s">%s</div>',
esc_url( $url ),
esc_url( $url )
);
return $result;
}, 10, 3 );
```
When you paste a Facebook post url, into the post content editor, it will also show the modified oEmbed result, with our snippet.
The oEmbed results are [cached](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-embed.php#L210) by default in the postmeta table, for `DAY_IN_SECONDS` (24 hours).
We can play with the [`oembed_ttl`](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-embed.php#L210) filter, like [here](https://wordpress.stackexchange.com/a/203558/26350), but in the meanwhile we can also filter the cached output with the [`embed_oembed_html`](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-embed.php#L239) filter.
Here's an example:
```
add_filter( 'embed_oembed_html', function( $cache, $url, $attr, $post_id )
{
// override the cached HTML result for Facebook posts
if( preg_match( '#https?://www\.facebook\.com/.*/posts/.*#i', $url ) )
$cache = sprintf(
'<div class="fb-post" data-href="%s">%s</div>',
esc_url( $url ),
esc_url( $url )
);
return $cache;
}, 10, 4 );
```
|
253,401 |
<p>I am using wordpress ajax and following code not passing parameter value <code>metakey: id</code> to <code>$_POST["metakey"]</code>. So <code>var_dump($_POST)</code> shows <code>array(0) { }</code> and <code>$_REQUEST</code> shows <code>array()</code></p>
<p>if I enter static value of variable in PHP function <code>$key=<any meta
key></code> then its works fine</p>
<pre><code>jQuery(".selectbox").change(function(){
var id = this.id;
// do a POST ajax call
$.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ({
action: "get-mata-value",
metakey: id
}),
success: function( response ) {
jQuery.each(response ,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
});
});
</code></pre>
<p>PHP:</p>
<pre><code>add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$result=
$wpdb->get_col( $wpdb->prepare(
"
SELECT DISTINCT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$key
) );
return($result);
exit();
}
</code></pre>
<p>EDIT:</p>
<p>Under chrome developer tool I see </p>
<blockquote>
<p>jquery.js?ver=1.12.4:4 XHR finished loading: POST</p>
</blockquote>
<p>with following error:</p>
<blockquote>
<p>jquery.js?ver=1.12.4:2 Uncaught TypeError: Cannot use 'in' operator to
search for 'length' in</p>
</blockquote>
|
[
{
"answer_id": 253406,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p>First of all you should read the codex on <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\"><strong>AJAX_in_Plugins</strong></a></p>\n\n<p>Secondly you should look at <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\"><strong>wp_localize_script</strong></a> to get the value for the admin-ajax url to your javascript.</p>\n\n<pre><code>$data = array(\n 'ajax_url' => admin_url( 'admin-ajax.php' )\n);\n\nwp_localize_script( 'ajax-script', 'ajax_object', $data );\n</code></pre>\n\n<p>In your javascript, you are then meant to reference the localized data</p>\n\n<pre><code>jQuery(\".selectbox\").change(function(){\n var id = this.id;\n\n // do a POST ajax call\n $.ajax({\n type: \"POST\",\n url: ajax_object.ajax_url,\n data: ({\n \"action\": \"get-mata-value\",\n \"metakey\": id\n }),\n success: function( response ) {\n\n }\n });\n});\n</code></pre>\n"
},
{
"answer_id": 253588,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 0,
"selected": false,
"text": "<p>I tried your code. Not sure why, but <code>this.id</code> doesn't return value for me. So instead try using <code>jQuery(this).attr('id')</code>.</p>\n\n<p>Also if this doesn't solve your problem, try <code>console.log(id)</code> before your ajax call and check what value you get.</p>\n"
},
{
"answer_id": 254006,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 0,
"selected": false,
"text": "<p>You are receiving an error in the jQuery plugin. I don't know why, but it seems to be the roadblock on your development. I looked at my wordpress installation, and I use the same version of jQuery, but without the error. </p>\n\n<p>I don't know if there is a plugin or theme that is causing a conflict. The usual remedy is to disable all plugins and themes and see if the problem goes away.</p>\n\n<p>You might also try enqueueing older versions of jQuery (if that's possible) to see if that clears up the problem.</p>\n\n<p>Perhaps it's the installation of wordpress that is broken. Could you do a fresh install of WP somewhere else? Your local machine might be a good candidate.</p>\n\n<p>I'm sorry I don't know why you're getting this error, it just seems clear that until you clear that up, you won't be able to see if your AJAX is working or not.</p>\n\n<p><strong>EDIT</strong>: I'm wondering if the error is occurring while the data is being sent, or when the data is being returned. In <code>get_mata_value()</code>, instead of \"return($result)\", try \"echo $result;\". And instead of \"exit();\" try \"wp_die();\". But instead of <code>$result</code> coming from the database, set it to a test value, like <code>$result = \"I get by with a little help from my friends\";</code></p>\n\n<p>I googled the error message from jQuery. See the last answer on this <a href=\"https://stackoverflow.com/questions/31149836/uncaught-typeerror-cannot-use-in-operator-to-search-for-length-in-trigge\">page</a>. I would change the first line of the change callback function from <code>var id=this.id;</code> to <code>var id=jQuery(this).id;</code></p>\n"
},
{
"answer_id": 254036,
"author": "Muhammad Muazzam",
"author_id": 95126,
"author_profile": "https://wordpress.stackexchange.com/users/95126",
"pm_score": 2,
"selected": true,
"text": "<p>The issue was with google api as stated in question by showing api related error message</p>\n\n<blockquote>\n <p>jquery.js?ver=1.12.4:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in</p>\n</blockquote>\n\n<p>So I have added following code snippet in theme functions.php that called previous version of google api. It has solved the issue of passing parameter value. All other code was already fine.</p>\n\n<pre><code> //Making jQuery Google API\n\n function modify_jquery() {\n\n if (!is_admin()) {\n\n // comment out the next two lines to load the local copy of jQuery\n\n wp_deregister_script('jquery');\n\n wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1');\n\n wp_enqueue_script('jquery');\n }\n\n }\n\n add_action('init', 'modify_jquery');\n</code></pre>\n"
}
] |
2017/01/21
|
[
"https://wordpress.stackexchange.com/questions/253401",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95126/"
] |
I am using wordpress ajax and following code not passing parameter value `metakey: id` to `$_POST["metakey"]`. So `var_dump($_POST)` shows `array(0) { }` and `$_REQUEST` shows `array()`
if I enter static value of variable in PHP function `$key=<any meta
key>` then its works fine
```
jQuery(".selectbox").change(function(){
var id = this.id;
// do a POST ajax call
$.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ({
action: "get-mata-value",
metakey: id
}),
success: function( response ) {
jQuery.each(response ,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
});
});
```
PHP:
```
add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$result=
$wpdb->get_col( $wpdb->prepare(
"
SELECT DISTINCT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$key
) );
return($result);
exit();
}
```
EDIT:
Under chrome developer tool I see
>
> jquery.js?ver=1.12.4:4 XHR finished loading: POST
>
>
>
with following error:
>
> jquery.js?ver=1.12.4:2 Uncaught TypeError: Cannot use 'in' operator to
> search for 'length' in
>
>
>
|
The issue was with google api as stated in question by showing api related error message
>
> jquery.js?ver=1.12.4:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
>
>
>
So I have added following code snippet in theme functions.php that called previous version of google api. It has solved the issue of passing parameter value. All other code was already fine.
```
//Making jQuery Google API
function modify_jquery() {
if (!is_admin()) {
// comment out the next two lines to load the local copy of jQuery
wp_deregister_script('jquery');
wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1');
wp_enqueue_script('jquery');
}
}
add_action('init', 'modify_jquery');
```
|
253,410 |
<p>hi i want to display posts by term.
first the code display all the posts:</p>
<pre><code> $aProjectArgs = array(
'post_type' => 'uni_project',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'asc'
);
</code></pre>
<p>so i add another part of code to display posts by term:</p>
<pre><code>$aProjectArgs = array(
'post_type' => 'uni_project',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'asc'
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => 43
)
)
);
</code></pre>
<p>but its not working its give me an error message<code>:Parse error: syntax error, unexpected ''tax_query''</code></p>
<p>can someone help me?</p>
|
[
{
"answer_id": 253411,
"author": "Md. Mrinal Haque",
"author_id": 111354,
"author_profile": "https://wordpress.stackexchange.com/users/111354",
"pm_score": 1,
"selected": false,
"text": "<p>put <code>,</code> in 'order' => 'asc' 'tax_query'</p>\n"
},
{
"answer_id": 253412,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 0,
"selected": false,
"text": "<p>Replace your code with this one.</p>\n\n<pre><code> $aProjectArgs = array(\n 'post_type' => 'uni_project',\n 'posts_per_page' => -1,\n 'orderby' => 'menu_order',\n 'order' => 'asc',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'post_tag',\n 'field' => 'id',\n 'terms' => 43\n )\n )\n );\n</code></pre>\n"
}
] |
2017/01/21
|
[
"https://wordpress.stackexchange.com/questions/253410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111459/"
] |
hi i want to display posts by term.
first the code display all the posts:
```
$aProjectArgs = array(
'post_type' => 'uni_project',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'asc'
);
```
so i add another part of code to display posts by term:
```
$aProjectArgs = array(
'post_type' => 'uni_project',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'asc'
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => 43
)
)
);
```
but its not working its give me an error message`:Parse error: syntax error, unexpected ''tax_query''`
can someone help me?
|
put `,` in 'order' => 'asc' 'tax\_query'
|
253,428 |
<p>I have had a look at the source code of Wordpress, as well as php.net for a possible answer. However, I was not able to get close to finding it.</p>
<p>For the source code, I was assuming I would find it in one of the many files I checked in the wp-includes folder. However, there are way! to many files to look through.</p>
<p>What I want to know if how does Wordpress manage to get Theme/Plugin/Template name and other information from the headers of the specific files? If it were XML data or PHP variables, it would make sense. However the data is places in PHP Comments! How does one read comments?</p>
<pre><code>/*
Theme Name: Twenty Sixteen
Theme URI: https://wordpress.org/themes/twentysixteen/
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Twenty Sixteen is a modernized take on an ever-popular WordPress layout Version: 1.2
License: GNU General Public License v2 or later
Text Domain: twentysixteen
*/
</code></pre>
<p>One question here on StackOverflow suggested the use of <code>getDocComment()</code> however now another question comes to me mind, first, how do we only get a specific block of comments? </p>
<p>Even if we manage to get all the content of the comment, how do we manage to get the "Theme Name" into a variable and so on?</p>
|
[
{
"answer_id": 253440,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>The function is called <a href=\"https://developer.wordpress.org/reference/functions/get_file_data/\" rel=\"nofollow noreferrer\"><code>get_file_data</code></a>, it uses a regular expression to parse the text and find headers.</p>\n"
},
{
"answer_id": 253444,
"author": "Matt Cromwell",
"author_id": 48338,
"author_profile": "https://wordpress.stackexchange.com/users/48338",
"pm_score": 0,
"selected": false,
"text": "<p>My previous answer was very close -- but then I realized <code>get_plugin_data()</code> only works in wp-admin. So I experimented, and this will give you everything you need:</p>\n\n<pre><code> $my_theme = wp_get_theme( 'twentyfifteen' );\n if ( $my_theme->exists() )\n\n echo '<p>Theme Author: ' . $my_theme['Author']. '</p>';\n\n if ( ! function_exists( 'get_plugins' ) ) {\n require_once ABSPATH . 'wp-admin/includes/plugin.php';\n }\n $pluginfile = ABSPATH . 'wp-content/plugins/give/give.php';\n $plugindata = get_plugin_data( $pluginfile );\n\n echo '<p>Plugin Name: ' . $plugindata['Name']. '</p>';\n</code></pre>\n"
}
] |
2017/01/21
|
[
"https://wordpress.stackexchange.com/questions/253428",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48443/"
] |
I have had a look at the source code of Wordpress, as well as php.net for a possible answer. However, I was not able to get close to finding it.
For the source code, I was assuming I would find it in one of the many files I checked in the wp-includes folder. However, there are way! to many files to look through.
What I want to know if how does Wordpress manage to get Theme/Plugin/Template name and other information from the headers of the specific files? If it were XML data or PHP variables, it would make sense. However the data is places in PHP Comments! How does one read comments?
```
/*
Theme Name: Twenty Sixteen
Theme URI: https://wordpress.org/themes/twentysixteen/
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Twenty Sixteen is a modernized take on an ever-popular WordPress layout Version: 1.2
License: GNU General Public License v2 or later
Text Domain: twentysixteen
*/
```
One question here on StackOverflow suggested the use of `getDocComment()` however now another question comes to me mind, first, how do we only get a specific block of comments?
Even if we manage to get all the content of the comment, how do we manage to get the "Theme Name" into a variable and so on?
|
The function is called [`get_file_data`](https://developer.wordpress.org/reference/functions/get_file_data/), it uses a regular expression to parse the text and find headers.
|
253,445 |
<p>I have a custom endpoint where I want to change HTTP response status to 404 in certain scenarios (e.g post does not exist). How can I do that? Here is an example of custom endpoint:</p>
<pre><code>function af_news_single( \WP_REST_Request $data ) {
global $wpdb;
$year = (int) $data['year'];
$month = (int) $data['month'];
$day = (int) $data['day'];
$slug = $data['slug'];
$date = "{$year}-{$month}-{$day}";
$news = $wpdb->get_row(
$wpdb->prepare(
"SELECT
DATE_FORMAT(post_date, %s) as `post_date`,
`post_title`,
`post_name`,
`post_content`
FROM {$wpdb->posts}
WHERE
`post_status` = 'publish' AND
`post_type` = 'post' AND
`post_name` = %s AND
`post_date` BETWEEN %s AND %s + INTERVAL 1 DAY
LIMIT 1
", '%Y-%m-%dT%TZ', $slug, $date, $date
)
);
if ( $news ) {
$news->post_title = qtranxf_translate( $news->post_title );
$news->post_content = wpautop( qtranxf_translate( $news->post_content ) );
} else { /* How to change response code? */ }
return [ 'data' => $news ];
}
</code></pre>
<p>How can I change response code in this function?</p>
|
[
{
"answer_id": 253472,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 6,
"selected": true,
"text": "<p>You can return a <code>WP_Error</code> object in which you define the status code. Here's a snippet from <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#return-value\" rel=\"noreferrer\">the REST API documentation</a>:</p>\n<pre><code>function my_awesome_func( $data ) {\n $posts = get_posts( array(\n 'author' => $data['id'],\n ) );\n\n if ( empty( $posts ) ) {\n return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );\n }\n\n return $posts[0]->post_title;\n}\n</code></pre>\n<p>In your case you could do something like:</p>\n<pre><code>return new WP_Error( 'page_does_not_exist', __('The page you are looking for does not exist'), array( 'status' => 404 ) );\n</code></pre>\n"
},
{
"answer_id": 312034,
"author": "Walf",
"author_id": 27856,
"author_profile": "https://wordpress.stackexchange.com/users/27856",
"pm_score": 4,
"selected": false,
"text": "<p>The simplest way is to do this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>return new WP_REST_Response(null, 404);\n</code></pre>\n<p>Note: this is still a JSON response containing <code>null</code> as the body. You can return a more useful data structure with error codes/messages, etc., or <a href=\"https://wordpress.stackexchange.com/a/386882/27856\">hook into the REST output filters</a> to output a blank <code>text/plain</code> response.</p>\n"
},
{
"answer_id": 388065,
"author": "Piotr Kucułyma",
"author_id": 147957,
"author_profile": "https://wordpress.stackexchange.com/users/147957",
"pm_score": 0,
"selected": false,
"text": "<p>I would not use:</p>\n<pre class=\"lang-php prettyprint-override\"><code>return new WP_REST_Response(null, 404);\n</code></pre>\n<p>I had an issue with hosting provider when I used status codes in this function. Somehow setting status code triggered mod_rewrite response.</p>\n<pre><code>Message: Access denied with code 406 (phase 3). Test 'REQUEST_URI|REQUEST_HEADERS|REQUEST_HEADERS_NAMES|ARGS|ARGS_NAMES|REQUEST_BODY' against '!@validateByteRange 0-31' is true.\n</code></pre>\n<p>It might not be and issue with wordpress but using:</p>\n<pre class=\"lang-php prettyprint-override\"><code>return new WP_REST_Response(null);\n</code></pre>\n<p>solved the problem.</p>\n<p>I'll just leave it here in case anyone encounters same problem.</p>\n"
}
] |
2017/01/21
|
[
"https://wordpress.stackexchange.com/questions/253445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67305/"
] |
I have a custom endpoint where I want to change HTTP response status to 404 in certain scenarios (e.g post does not exist). How can I do that? Here is an example of custom endpoint:
```
function af_news_single( \WP_REST_Request $data ) {
global $wpdb;
$year = (int) $data['year'];
$month = (int) $data['month'];
$day = (int) $data['day'];
$slug = $data['slug'];
$date = "{$year}-{$month}-{$day}";
$news = $wpdb->get_row(
$wpdb->prepare(
"SELECT
DATE_FORMAT(post_date, %s) as `post_date`,
`post_title`,
`post_name`,
`post_content`
FROM {$wpdb->posts}
WHERE
`post_status` = 'publish' AND
`post_type` = 'post' AND
`post_name` = %s AND
`post_date` BETWEEN %s AND %s + INTERVAL 1 DAY
LIMIT 1
", '%Y-%m-%dT%TZ', $slug, $date, $date
)
);
if ( $news ) {
$news->post_title = qtranxf_translate( $news->post_title );
$news->post_content = wpautop( qtranxf_translate( $news->post_content ) );
} else { /* How to change response code? */ }
return [ 'data' => $news ];
}
```
How can I change response code in this function?
|
You can return a `WP_Error` object in which you define the status code. Here's a snippet from [the REST API documentation](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#return-value):
```
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );
}
return $posts[0]->post_title;
}
```
In your case you could do something like:
```
return new WP_Error( 'page_does_not_exist', __('The page you are looking for does not exist'), array( 'status' => 404 ) );
```
|
253,473 |
<p>Suppose I have created an app that uses WordPress REST API plugin and displays the posts from the WordPress site.</p>
<p>Now, if I find the WordPress site which is having the WP REST API plugin and I am able to fetch the data from it (only displaying the data into the app, not storing it). Is it legal to do so as per WordPress or REST API license?</p>
|
[
{
"answer_id": 253472,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 6,
"selected": true,
"text": "<p>You can return a <code>WP_Error</code> object in which you define the status code. Here's a snippet from <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#return-value\" rel=\"noreferrer\">the REST API documentation</a>:</p>\n<pre><code>function my_awesome_func( $data ) {\n $posts = get_posts( array(\n 'author' => $data['id'],\n ) );\n\n if ( empty( $posts ) ) {\n return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );\n }\n\n return $posts[0]->post_title;\n}\n</code></pre>\n<p>In your case you could do something like:</p>\n<pre><code>return new WP_Error( 'page_does_not_exist', __('The page you are looking for does not exist'), array( 'status' => 404 ) );\n</code></pre>\n"
},
{
"answer_id": 312034,
"author": "Walf",
"author_id": 27856,
"author_profile": "https://wordpress.stackexchange.com/users/27856",
"pm_score": 4,
"selected": false,
"text": "<p>The simplest way is to do this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>return new WP_REST_Response(null, 404);\n</code></pre>\n<p>Note: this is still a JSON response containing <code>null</code> as the body. You can return a more useful data structure with error codes/messages, etc., or <a href=\"https://wordpress.stackexchange.com/a/386882/27856\">hook into the REST output filters</a> to output a blank <code>text/plain</code> response.</p>\n"
},
{
"answer_id": 388065,
"author": "Piotr Kucułyma",
"author_id": 147957,
"author_profile": "https://wordpress.stackexchange.com/users/147957",
"pm_score": 0,
"selected": false,
"text": "<p>I would not use:</p>\n<pre class=\"lang-php prettyprint-override\"><code>return new WP_REST_Response(null, 404);\n</code></pre>\n<p>I had an issue with hosting provider when I used status codes in this function. Somehow setting status code triggered mod_rewrite response.</p>\n<pre><code>Message: Access denied with code 406 (phase 3). Test 'REQUEST_URI|REQUEST_HEADERS|REQUEST_HEADERS_NAMES|ARGS|ARGS_NAMES|REQUEST_BODY' against '!@validateByteRange 0-31' is true.\n</code></pre>\n<p>It might not be and issue with wordpress but using:</p>\n<pre class=\"lang-php prettyprint-override\"><code>return new WP_REST_Response(null);\n</code></pre>\n<p>solved the problem.</p>\n<p>I'll just leave it here in case anyone encounters same problem.</p>\n"
}
] |
2017/01/22
|
[
"https://wordpress.stackexchange.com/questions/253473",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111492/"
] |
Suppose I have created an app that uses WordPress REST API plugin and displays the posts from the WordPress site.
Now, if I find the WordPress site which is having the WP REST API plugin and I am able to fetch the data from it (only displaying the data into the app, not storing it). Is it legal to do so as per WordPress or REST API license?
|
You can return a `WP_Error` object in which you define the status code. Here's a snippet from [the REST API documentation](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#return-value):
```
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );
}
return $posts[0]->post_title;
}
```
In your case you could do something like:
```
return new WP_Error( 'page_does_not_exist', __('The page you are looking for does not exist'), array( 'status' => 404 ) );
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.