hindisong.cc
hindisong.cc

Reputation: 101

Move a particular div to top programmatically in wordpress in all posts

I have a particular div in all wordpress posts, I want to move them to the top , so that its the first paragraph. I have more than 3000 posts in the wordpress site. So moving each one isn't an option for me. I tried this,

function add_this_script_footer(){
$specialDiv = document.getElementById("medtab");
$movedDiv = specialDiv;
$entryContent = document.getElementsByClassName("entry-content")[0];
entryContent.insertAdjacentElement('afterbegin', movedDiv);
specialDiv.remove();
}

add_action('wp_footer', 'add_this_script_footer');

have added this to the code snippet plugin, but doesn't work.

This is the error am getting when adding it to functions.php

syntax error, unexpected 'var' (T_VAR)

Upvotes: 0

Views: 1037

Answers (1)

Ozgur Sar
Ozgur Sar

Reputation: 2204

You can write some simple javascript and place it in the footer to programmatically remove the specified div from your content and move it to the top of the content.

First add your JS to the footer. (This goes into your functions.php of your child theme. You can also use Code Snippets plugin to add it if are not using a child theme)

function add_this_script_footer(){ ?>
//YOUR JS CODE HERE
}

add_action('wp_footer', 'add_this_script_footer'); ?>

As you didn't share your code, I'm assuming that your special div has an id. In that case you can select it with.

var specialDiv = document.getElementById("your-div-id");
var movedDiv = specialDiv; // Copy moved Div to a new variable

You can then remove it using remove() method.

specialDiv.remove();

Finally, you can insert the movedDiv to the beginning of entry-content (Which should be the main content area div) by using insertAdjacentElement()

var entryContent = document.getElementsByClassName("entry-content")[0];
entryContent.insertAdjacentElement('afterbegin', movedDiv);

EDIT2: The problem was, movedDiv had to be "cloned" with .cloneNode

add_action( 'wp_footer', function () { ?>
<script>
  var specialDiv = document.getElementById("medtab");
  var movedDiv = specialDiv.cloneNode(true);
  var entryContent = document.getElementsByClassName("entry-content")[0];
  entryContent.insertAdjacentElement('afterbegin', movedDiv);
  specialDiv.remove();
</script>
<?php } );

Upvotes: 1

Related Questions